Reading a variable from Perl

I have many lines stored in a single variable in Perl.

I would like to know if these lines can be read using the <> operator.

+7
source share
3 answers

If you really need to, you can open a descriptor file for it.

use strict; use warnings; my $lines = "one\ntwo\nthree"; open my $fh, "<", \$lines; while( <$fh> ) { print "line $.: $_"; } 

Alternatively, if you already have the material in memory, you can simply split it into an array:

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

It will probably be easier to read and maintain the line.

+14
source

Yes. As described in perldoc -f open , you can open file descriptors for scalar variables.

 my $data = <<''; line1 line2 line3 open my $fh, '<', \$data; while (<$fh>) { chomp; print "[[ $_ ]]\n"; } # prints # [[ line1 ]] # [[ line2 ]] # [[ line3 ]] 
+7
source

I found a useful alternative,
it does not use <> but works as if it did

 for (split /^/, $lines) { ... } 

http://www.perlmonks.org/?node_id=745018

0
source

All Articles