[BNE-PM] The Perl one-liner

Derek Thomson derek at wedgetail.com
Thu Sep 19 04:55:24 CDT 2002


Anthony Thyssen wrote:
> A much simpler way of doing this is to use the shell quoting to
> include your shell veriable into the perl code.  I do this all the time
> in shell scripts.

> 
>    ls | perl -ne "print if m'$pattern'"

I've got a simpler answer ... don't write shell scripts! Seriously, I 
got sick of all the porting problems (each tool has different abilities, 
restrictions and bugs on each platform), and the fact that shell is just 
no good once you need even a simple list, let alone complex data structures.

So, I just do everything in Perl, apart from shell scripts that follow 
this form:

#!/bin/sh

# Set some environment variables and check config stuff

# Run a program

# Do whatever clean up needs to be done

... in other words, just the occasional convenience wrapper. As soon as 
I need a loop, or an "if", I throw it away and do it in Perl. Then it 
works properly, everywhere (even on Windows).

And you don't have all this painful mucking about with quotes!

So, if I were in the middle of my Perl program, and suddenly needed to 
list the files that matched a regular expression, I would just:

my $dir = DirHandle->new('.');

my @files = grep /$pattern/, $dir->read;

$dir->close;

... and the matches are now in @files, which I can then do whatever I 
like with. (The Perl "grep" function selects items from a list based on 
the pattern, the "read" method is smart enough to know that you want all 
the files in that context, and of course you would need to have imported 
DirHandle with "use DirHandle;").

No need to call "ls" from Perl (which I see a lot), and no need to call 
Perl from shell. I will go as far as to say there's rarely any need to 
invoke a standard Unix command from Perl - there's a module in the 
standard distro for pretty much everything. Calling "ls" or "cp" or 
whatever from Perl just makes your code non-portable, and very slow ... 
and forcing yourself not to do this is a good way to learn about the 
standard modules!

--
D.




More information about the Brisbane-pm mailing list