SPUG:Best One-Liners and Scripts for UNIX

SPUG-list-owner tim at consultix-inc.com
Thu Apr 17 16:48:38 CDT 2003


On Thu, Apr 17, 2003 at 01:38:10PM -0700, Cantrall, Christopher W wrote:
> So I banged out this Llama-level number stripper:
> 
> #!/usr/bin/perl -w
> use strict;
> 
> my $filename = shift @ARGV;
> open (FH, $filename) or die $!;
> my @file = <FH>;
> my @out;
> 
> push @out, "#!/usr/bin/perl\nuse strict;\n\n";
> foreach my $line (@file) {
>     $line =~ s/^\s*\d{3}:\s//;
>     push @out, $line;
> }
> print @out;
> 
> 
> It's the sort of thing I love about perl: solve a quick problem in a
> readable, maintable way. And I don't need to add the she-bang line
> manually.

I agree!  The only thing you'll have to add manually is the
(all-important) -w perl invocation option your script leaves
out! 8-}

But dude, you're writing much more code than is necessary!

You could take advantage of the implicit (-p) loop, with its
implicit open(), and dispense with the array, and make it a two-liner:

#!/usr/bin/perl -wp
BEGIN { print "#!/usr/bin/perl -wp\nuse strict;\n\n"; }
s/^\s*\d{3}:\s//;
# print;  # courtesy of -p option

You might also want to convert spaces to tabs, if you prefer
tabs in your code, using Text::Tabs::unexpand().

-Tim
*------------------------------------------------------------*
|  Tim Maher (206) 781-UNIX  (866) DOC-PERL  (866) DOC-UNIX  |
|  CEO, JAWCAR ("Just Another White Camel Award Recipient")  |
|  tim at Consultix-Inc.Com  TeachMeUnix.Com  TeachMePerl.Com   |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-*
|  Watch for my  Book: "Minimal Perl for Shell Programmers"  |
*------------------------------------------------------------*



More information about the spug-list mailing list