[BNE-PM] The Perl one-liner
Don.Simonetta at mincom.com
Don.Simonetta at mincom.com
Thu Sep 19 16:53:55 CDT 2002
Totally agree with you Derek.
My only comment is if you don't want to go to the trouble of importing
DirHandle, you could use the standard perl functions of opendir &
readdir.
-----Original Message-----
From: owner-brisbane-pm-list at pm.org
[mailto:owner-brisbane-pm-list at pm.org] On Behalf Of derek at wedgetail.com
Sent: Thursday, 19 September 2002 19:55
To: anthony at cit.gu.edu.au
Cc: brisbane-pm-list at happyfunball.pm.org
Subject: Re: [BNE-PM] The Perl one-liner
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.
--
This transmission is for the intended addressee only and is confidential information. If you have received this transmission in error, please delete it and notify the sender. The contents of this e-mail are the opinion of the writer only and are not endorsed by the Mincom Group of companies unless expressly stated otherwise.
More information about the Brisbane-pm
mailing list