Bharath has asked for the wisdom of the Perl Monks concerning the following question:

How can i extract a particular field from a given line. example: 07870635509,3,0,29052002,DORMANT,05011998,1,2,128,0,0,0 In the above line i have to extract 5th field. the size of each field varies from one line to another. so i would like to extract the field using its field number. Thanks for the help

Replies are listed 'Best First'.
Re: Extracting field from a line
by jbrugger (Parson) on Jul 14, 2005 at 05:38 UTC
    #!/usr/bin/perl -w use strict; my $str = "07870635509,3,0,29052002,DORMANT,05011998,1,2,128,0,0,0"; my @arr = split(',', $str); print "field5 = $arr[4]";
    "We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.
      I usually do this, which is much the same:
      my $field5 = [split(/,/,$str)]->[4];
Re: Extracting field from a line
by NetWallah (Canon) on Jul 14, 2005 at 05:45 UTC
    In a more general case, your line may contain quoted commas, or escaped commas, causing undesired or unexpected field splitting.

    I'd suggest using Text::CSV , in order to create more robust code.

         "Income tax returns are the most imaginative fiction being written today." -- Herman Wouk