Column handling in Perl

Problem

During my first encounters with Perl many years ago, I asked how can I get a specific column.

It was so easy in AWK! ๐Ÿ˜‰



Solution

Well here it is in Perl – see example tab.

BTW you can always write an awkscript and run it through a2p – very good for learning Perl! ๐Ÿ™‚



Example


Show column 1:

perl -ane 'print $F[0]."n";'

Show column 2:

perl -ane 'print $F[1]."n";'

Show last column:

perl -ane 'print $F[$#F]."n";'

Show last but one column:

perl -ane 'print $F[($#F-1)]."n";'

So you just run your program, or cat your file, etc and pipe it through this code to get specific column.



Reference

[tags]Perl column handling, Awk to Perl, a2p, Perl Coding School[/tags]



Comments (2)

  1. Use split:
    my @columns = split /t/, $input;
    my $third_column = $columns[2];

  2. […] Perl Coding School ยป Column handling in Perl (tags: Perl column handling a2p Coding School) […]

Leave a Reply

Your email address will not be published. Required fields are marked *