You're viewing a comment by poletti and its responses.

poletti Permalink
August 25, 2009, 16:27

A trick that is very useful in one-liners is using the closing-opening braces and avoid END blocks. For example, this:

perl -lne '$a++ if /regex/; END {print $a+0}'

can be turned into this:

perl -lne '$a++ if /regex/}{print $a+0'

And there's more! You can actually turn the "n" into a "p" and save a few more keystrokes using $_:

perl -lpe '$a++ if /regex/}{$_=$a+0'

This takes advantage of the code that is automagically put around your code (more or less...):

while () {
your-code-here
;print; # if -p, otherwise no print
}

which becomes:

while () {
$a++ if /regex/}{$_=$a+0
;print;
}

i.e.

while () {
$a++ if /regex/
}

{
$_=$a+0;
print;
}

I seem to remember that Abigail is to be credited for this.

Comment Responses

thisisraja Permalink
September 21, 2011, 00:01

crazy! guys...

Reply To This Comment

(why do I need your e-mail?)

(Your twitter name, if you have one. (I'm @pkrumins, btw.))

Type the word "linux": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.