On Dec 31, 2007 5:56 PM, Jean-Rene David <[EMAIL PROTECTED]> wrote: > Hi, > > I wonder what idioms are available to loop through > the lines stored in a scalar variable. I guess I'm > looking for something analogous to these idioms > for files and arrays respectively: > > while(<FH>) { > # do stuff > } > > foreach (@array) { > # do stuff > } > > When I had to do this I split the scalar in an > array: > > @array = split "\n", $scalar; > foreach (@array) { > # do stuff > } snip
I would say the most common way would be to use the list returned by split in the for directly: #!/usr/bin/perl use strict; use warnings; my $s = "foo\nbar\nbaz\nquux\n"; my $i; for my $line (split "\n", $s) { print $i++, " $line\n"; } But you could also use a regex with the g and m modifiers in scalar context if you were worried about space issues (e.g. the scalar holds a gigabyte of data you don't want to duplicate) #!/usr/bin/perl use strict; use warnings; my $s = "foo\nbar\nbaz\nquux\n"; my $i; while ($s =~ /^(.*)$/gm) { my $line = $1; print $i++, " $line\n"; } Also, it is a good idea to use the strict and warnings pragmas (like I did in the code above) and to use named variables in your for loops. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/