For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > October 2007 > getting nth column of a string









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author getting nth column of a string
Mahurshi Akilla

2007-10-28, 7:00 pm

is there a way to get the "nth" column of a string in perl, similar to
awk '{print $col_no}' in awk ?

John W. Krahn

2007-10-28, 7:00 pm

Mahurshi Akilla wrote:
>
> is there a way to get the "nth" column of a string in perl, similar to
> awk '{print $col_no}' in awk ?


AWK does not have a 'col_no' variable so what is it that you are trying
to do?

I assume that you meant:

awk '{print $2}'

which would print the second field of the current record for each record
in the file/stream?

The Perl equivalent to that is:

perl -lane'print $F[1]'



John
--
use Perl;
program
fulfillment
Chas. Owens

2007-10-28, 7:00 pm

On 10/28/07, Mahurshi Akilla <mahurshi@gmail.com> wrote:
> is there a way to get the "nth" column of a string in perl, similar to
> awk '{print $col_no}' in awk ?

snip

If I remember my awk correctly $col_no (e.g. $2) gives you the nth
space delimited field in the string (counting multiple spaces as a
single delimiter). The split function in Perl returns a list of items
delimited by the first argument and if that argument is a single space
it counts multiple spaces as one delimiter. You can extract the nth
element from this list using the indexing operators:

my $second_col = (split ' ', $string)[1];

Split's default arguments are ' ' and $_ so you can write this awk

awk '{print $2}' file

like this

perl -lne 'print((split)[1])' file

or this

perl -lpe '$_=(split)[1]' file

or even this

perl -pale '$_=$F[1]' file
Oryann9

2007-10-28, 7:00 pm

is there a way to get the "nth" column of a string in perl, similar to=0Aaw=
k '{print $col_no}' in awk ? =0A=0A###############################=0A
=0ATher=
e are multiple ways, but here are two examples:=0AIn the first example, spl=
it is what you need to pay attention to.=0AIn the second example, @F is th=
e key here. =0A=0A$ perl -le 'my $string =3D qq(a b c d); print $string; pr=
int +(split)[2,3], for $string;'=0Aa b c d=0Acd=0A=0A$ echo "a b c d"| perl=
-nae 'print "@F[2,3]\n";'=0Ac d=0A=0A=0A=0A=0A=0A_____________________
____=
_________________________=0ADo You Yahoo!?=0ATired of spam? Yahoo! Mail ha=
s the best spam protection around =0Ahttp://mail.yahoo.com
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com