Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from variable in Perl

I have a lot of lines stored in a single variable in Perl.

I would like to know if it is possible to read those lines using <> operator.

like image 829
user1544745 Avatar asked Jul 23 '12 02:07

user1544745


2 Answers

If you really must, you can open a filehandle to it.

use strict;
use warnings;

my $lines = "one\ntwo\nthree";
open my $fh, "<", \$lines;

while( <$fh> ) { 
    print "line $.: $_";
}

Alternatively, if you've already got the stuff in memory anyway, you could just split it into an array:

my @lines = split /\n/, $lines;   # or whatever
foreach my $line( @lines ) { 
    # do stuff
}

That would probably be easier to read and maintain down the line.

like image 143
friedo Avatar answered Oct 24 '22 18:10

friedo


Yes. As documented in perldoc -f open, you can open filehandles to scalar variables.

my $data = <<'';
line1
line2
line3

open my $fh, '<', \$data;
while (<$fh>) {
    chomp;
    print "[[ $_ ]]\n";
}

# prints
# [[ line1 ]]
# [[ line2 ]]
# [[ line3 ]]
like image 41
ephemient Avatar answered Oct 24 '22 18:10

ephemient