Re: more on 1 liner perl/awk
On Mon, Mar 10, 2003 at 12:26:47PM -0800, Osamu Aoki wrote:
> Another guy replied with
>
> perl -ne 'if ((my @fields = split)[1] eq "1957") { print "$fields[2]\n" }'
>
> I tested all:
>
> osamu@goofy:osamu$ perl -ne 'if ((my @f = split)[1] eq "1957") { print "$f[2]\n" }' < mat.txt
> 111
> osamu@goofy:osamu$ perl -ne '@f = split; if ($f[1] eq "1957") { print "$f[2]\n" }' < mat.txt
> 111
> osamu@goofy:osamu$ perl -ne 'if ((@f = split)[1] eq "1957") { print "$f[2]\n" }' < mat.txt
> 111
>
> For 1 liner, I guess local variable does not make much difference. So
> the last one is shortest.
>
> Does anyone else has shorter trick?
(All of this is untested.)
Well, you can clearly save some keystrokes by using a postfix statement
modifier rather than a block:
perl -ne 'print "$f[2]\n" if (@f = split)[1] eq "1957"' < mat.txt
You can simplify the print using the -l switch:
perl -lne 'print $f[2] if (@f = split)[1] eq "1957"' < mat.txt
Then you could use -a to do the split for you (use -F'\t' as well if the
default behaviour of splitting on whitespace is too loose for you):
perl -lane 'print $F[2] if $F[1] eq "1957"' < mat.txt
Then there are the usual tricks of eliminating whitespace and so on. In
fact, all the whitespace in the arguments to perl in the line above can
be removed if you feel so inclined:
perl -lane'print$F[2]if$F[1]eq"1957"' < mat.txt
Shorter solutions may be possible.
Google for "Perl Golf" if you're interested in this kind of thing: the
art of solving problems in the fewest (key)strokes.
Cheers,
--
Colin Watson [cjwatson@flatline.org.uk]
Reply to: