Perl's side of "for i in `cat file` do echo $i
In bash we have:
for i in `cat file` ; do
#do something here for example
echo $i
done;
How can I do that in a perl script?
I tried it with
#! /usr/bin/perl
use warnings;
use strict;
my $lines;
while (<>) { $lines .= $_ if 3 .. 5; } continue { close ARGV if eof; }
print $lines;
but it does not loop through them; it prints all lines from file on first run.
Thank you.
EDIT: Yes, but it still does not loop through them; the script tak开发者_StackOverflow社区es all variables and if for example I have
print "Header here\n";
print $lines;
print "Footer here\n\n";
and my variables file contains
line1
line2
line3
line4
etc...
it prints:
Header here
line1
line2
line3
line4 etc..
Footer here
instead of
Header here
line1
Footer here
Header here
line2
Footer here
Header here
line3
Footer here
Header here
line4
Footer here
etc...
Trying again:
Replace your $lines .= $_
with push @lines, $_
.
Then where you print, do:
for (@lines) {
print "Header here\n";
print $_;
print "Footer here\n\n";
}
instead of printing $lines, etc.
Though it sounds like you don't want the stuff selecting only lines 3 through 5; if that's the case, your whole program should just be:
use strict;
use warnings;
while (<>) {
print "Header here\n";
print $_;
print "Footer here\n\n";
}
Bash:
#!/usr/bin/env bash
while read i ; do
echo $i
done < file
Perl:
#!/usr/bin/env perl
use strict; use warnings;
open(my $fh, '<', 'file') or die $!;
while (my $i = <$fh>){
print $i;
}
close($fh) or die $!;
You're taking <> apart and then immediately putting it back together with the .= concatenate operator. If you want to do something to each line, such as print a header or footer, then you do it inside the loop.
It's possible that your input record separator is wrong and <> is not really going through multiple times. Print something inside the loop, such as ++$count, to see how many times you actually entered the loop. You might have to change your IRS, which is the $/ variable.
I am not sure what your after. But if I wanted to achieve the same in Perl on stdin, as you have in your bash
script I would do something like this:
#! /usr/bin/perl
use warnings;
use strict;
while(<>)
{
# Do something to $_ e.g. print lines 3 through 5
print if 3 .. 5;
}
Bash:
for i in `cat file` ; do
#do something here for example
echo $i
done;
Perl:
#!/usr/bin/perl -w
use strict;
while (<>) {
print $_;
}
man perlvar for more information on the $_ variable
精彩评论