I'm in the process of learning Perl and am trying to write a script that takes a pattern and list of files as command line arguments and passes them to a subroutine, the subroutine then opens each file and prints the lines that match the pattern. The code below works; however, it stops after printing the lines from the first file and doesn't even touch the second file. What am I missing here?
#!/usr/bin/perl
use strict;
use warnings;
sub grep_file
{
my $pattern = shift;
my @files = shift;
foreach my $doc (@files)
{
open FILE, $doc;
while (my $line = <FILE>)
{
if ($line =~ m/$pattern/)
{
print $line;
}
}
}
grep_file @ARGV;
Shift pops an element from your parameter (see: http://perldoc.perl.org/functions/shift.html).
So @files can only contain one value.
Try
sub foo
{
my $one = shift @_;
my @files = @_;
print $one."\n";
print @files;
}
foo(@ARGV);