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

Ok so I have some flat file databases that I will need to read into an array. One entry per line and pipe delimited. Like this:
This | Is | An | Entry | //Path/To/File.pdf This | Is | Entry | 2 | //Path/To/File2.pdf
I know how to read either the pipe delimited first line or the entire line into an array. But the only part I need is the last entry. Is there a way to read each entry into an array and go to the next line after I get done with the first one? Then I could just take every nth element and have an array with file paths.

Replies are listed 'Best First'.
Re: Reading from files
by roboticus (Chancellor) on Mar 30, 2012 at 02:08 UTC

    Hellhound4:

    You can use something like this:

    $ cat t.pl #!/usr/bin/perl use strict; use warnings; while (<DATA>) { my @f = split /\s+/, $_; my $last = pop @f; print $last, "\n"; } __DATA__ the quick red fox jumped over the lazy brown dog. Now is the time for all men to come to the aid of their party. $ perl t.pl fox lazy is all to their party.

    You could use shift to get the first column, or just use normal array indexing to get any column you like.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: Reading from files
by NetWallah (Canon) on Mar 30, 2012 at 04:02 UTC
    perl -ne 'my @x=split /\|\s/,$_; my $last=$x[$#x];print qq|$last\n|' Y +OUR.File.Name.here

                 All great truths begin as blasphemies.
                       ― George Bernard Shaw, writer, Nobel laureate (1856-1950)

Re: Reading from files
by tobyink (Canon) on Mar 30, 2012 at 06:11 UTC

    Another way to do it...

    #!/usr/bin/perl use Data::Dumper; my @paths = map { chomp; m{\|\s*([^|]+)$}; $1 } <DATA>; print Dumper \@paths; __DATA__ This | Is | An | Entry | //Path/To/File.pdf This | Is | Entry | 2 | //Path/To/File2.pdf
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: Reading from files
by Anonymous Monk on Mar 30, 2012 at 04:08 UTC
    Or maybe something like this:
    my %table; while (<DATA>) { chomp; my @f = split / \| /; my $i = 0; while(@f){ push @{$table{$i}}, shift @f; ++$i; } } use Data::Dumper; print Dumper \%table; print "\n=>> Paths:\n", join $/, @{$table{4}}; __DATA__ This | Is | An | Entry | //Path/To/File.pdf This | Is | Entry | 2 | //Path/To/File2.pdf
Re: Reading from files
by JavaFan (Canon) on Mar 30, 2012 at 09:00 UTC
    $ cat data This | Is | An | Entry | //Path/To/File.pdf This | Is | Entry | 2 | //Path/To/File2.pdf $ perl -F'\x7C\s' -ane'print$F[-1]' data //Path/To/File.pdf //Path/To/File2.pdf $ cut -d\| -f5 data|sed -es/^\ // # Shell solution //Path/To/File.pdf //Path/To/File2.pdf $