[Novalug] Tutorials

Kevin Dwyer kevin at pheared.net
Sat Dec 16 22:06:43 EST 2006


On Sat, Dec 16, 2006 at 07:38:07PM -0500, Rob Payne wrote:
> On Sat, Dec 16, 2006 at 01:07:40PM -0500, Kevin Dwyer wrote:
> > On Sat, Dec 16, 2006 at 12:17:30PM -0500, James Ewing Cottrell 3rd wrote:
> > > For example, the "print the second field" script above can be expressed 
> > > as a one-liner in Perl as: ps -ef | perl -lane 'print $F[1]'
> > 
> > This is precisely what keeps me from ever writing things in perl.
> > 
> > I.E.: Just where the hell did $F come from?  I guess $_ was already
> > spoken for.
> 
> Well, since this is a thread on tutorials, maybe you can offer some
> advice instead of just criticism?  If you prefer another language,
> maybe offer some code in that one.

It can be done in any number of languages.  perl is just full of
shortcuts so that it can fit in one-line.

Here's python in one line:

ps -ef | python -c 'import sys; print "\n".join([line.split()[1] for line in sys.stdin])'

Python isn't meant to be written in one line though, which is why that's
ugly.  Something better would look like this:

import sys
for line in sys.stdin:
    try:
        print line.split()[1]  
    except IndexError:
        pass # This is just to be extra safe.  Unnecessary if you can
             # trust that the input always has enough fields.

And you could make perl look like that too, but no one does because it's
some sort of faux pas.  (Perl people will say: Why bother when I can do
it in one line?  So it's a perspective thing, or perhaps a function of
how deranged one's mind is.)

-kpd



More information about the Novalug mailing list