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.
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.
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 ]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With