[BNE-PM] The Perl one-liner

Derek Thomson derek at wedgetail.com
Wed Sep 18 21:04:53 CDT 2002


Mike, can you please post to the list, not just to me? That way, the 
discussion benefits everyone. Again, I'm replying to the list. Call me 
rude, but I don't want to explain BEGIN and END twice!

Mike Bissett wrote:
>  
> I figured i was wrong with the $_ ... doh ! .. but do you 
> know of anyway to pass args to a one liner though ? 
> if you try to pass them on the perl command line it 
> assumes there files ? 

Like I said, you don't need to use @ARGV on the command line - you just 
put the pattern straight into the code!

Is this for some other problem? Context, please!

If you wanted to do this for some reason, wouldn't it just be:

$ ls | perl -e '$p = shift @ARGV; while (<>) {print if /$p/}' Foo

??

Notice that we can't use the -n option, as we don't want the "shift 
@ARGV" in the loop! Another way around the "start/finish" problem with 
"-n" and "-p" is to use BEGIN and END blocks, which execute code when a 
program starts, and when it finishes.

$ ls | perl -ne 'BEGIN {$p = shift @ARGV} print if /$p/' Foo

... but I honestly can't see what this gains you over:

$ ls | perl -ne 'print if /Foo/'

... unless you want to be able to dynamically set the pattern from 
another source as an argument. But at that point it's time to start 
considering writing something like my little pgrep program - you don't 
want to have to type this stuff over and over!

--
D.




More information about the Brisbane-pm mailing list