There are the ways halley mentions (Re^2: Empowered by Perl) that are not at all involved. There are many other ways as well. I'm offering some of those others, but it's still not an exhaustive list of ways to do this.
If you're not tied to your syntax, try option 0. If you are, try option 1 or option 2. Note the localization of @ARGV, which is important if you need to specify the content file in the program and still need your command-line arguments. Option 1 always returns a list, so you get a count of lines in scalar context. Option 2 returns whatever the diamond operator read depending on the sub's context. It can be used to read all lines in list context or one line at a time, iteratively, in scalar context.
If you don't need to specify the file you need the contents from in the program and don't care about mangling @ARGV for other uses you can use option 3, which is what automatic @ARGV handling by <> is for. Note that will do the same for as many files as specified in @ARGV and will implicitly shift them off the array.
Option 4 is reminiscent of both Option 0 and options 1/2. It lets you specify a single filename on the command line so you don't have your global @ARGV messed with, but it doesn't use a sub.
Update: Following the same thinking as 0 through 4, option 5 is left for an exercise: Take a command-line argument and pass it to the subroutine from Option 1 or Option 2.
Option 0:
Option 1:
Option 2:
Option 3:
Option 4:
Another approach is to just return what you actually want if you're not looking for all the contents anyway:
#!usr/bin/perl
use warnings;
use strict;
sub grepfile {
local @ARGV = ( $_[1] );
return grep /$_[0]/, <>;
}
my @text = grepfile 'important', './grepfile';
print @text, "\n";
print @ARGV, "\n";
Of course, this is not the prettiest Perl code out there. People might complain that you're messing with your tools in ways other than intended. Others would counter, though, that that's what happens with powerful, successful software.
|