Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Accessing Tab Delimited Field in Perl One-Liner

by neversaint (Deacon)
on Jun 01, 2009 at 01:23 UTC ( #767152=perlquestion: print w/replies, xml ) Need Help??
neversaint has asked for the wisdom of the Perl Monks concerning the following question:

Given such data (mydat.txt)
foo 1.02 bar 0 qux 2.33 tuq 0
The following is the typicall AWK ways to access field, by printing lines where the value of second column is 0 (zero).
$ awk '$2==0; {print}' mydat.txt
What's Perl one-liner way to do it?

neversaint and everlastingly indebted.......

Replies are listed 'Best First'.
Re: Accessing Tab Delimited Field in Perl One-Liner
by jwkrahn (Monsignor) on Jun 01, 2009 at 01:32 UTC

      Dang, -a/-F was what I was forgetting.

      For anyone who, like me, constantly forgets the commandline arguments, perldoc perlrun is your friend.

      Just another way if you forgot about -a (autosplit), slightly longer, but is runnable code within a script...
      perl -ne "(split)[1] || print" temp.txt #same thing... perl -ne "print if !((split)[1]);" temp.txt
      A Perl variable evaluates to false if either: undefined, numeric zero or "" (empty string).

      Update: also of note: default split operates on whitespace which is (\s\t\f\r\n). Above would work fine with combination of spaces and tabs between tokens.

Re: Accessing Tab Delimited Field in Perl One-Liner
by aufflick (Deacon) on Jun 01, 2009 at 01:32 UTC

    There is for sure going to be a shorter more golf-ish solution, but the obvious one is:

    perl -ne '@cols = split /\t/; print if $cols[1] == 0' mydat.txt
    • -n means iterate the next block of code over the supplied files one line at a time (where line means whatever is separated by the value of $/ which is the newline of your platform by default). The text line is presented in the variable $_ with a newline.
    • -e means interpret the next commandline argument as a chunk of code.
    • Many builtins, such as split, print and // regex matching, operate on $_ by default if no string/list argument is given.
Re: Accessing Tab Delimited Field in Perl One-Liner
by citromatik (Curate) on Jun 01, 2009 at 06:57 UTC

    BTW... your awk version is terribly verbose :-)

    awk '$2==0' mydat.txt


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://767152]
Approved by aufflick
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2017-03-30 06:38 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (353 votes). Check out past polls.