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

Revered MOnks,
I am trying to do the following:
a.there is a one line file with the following format:
data1:data2:data3:data4
b. i want to read in the 4th element i.e the last element
I am currently doing the following:
@result=split(/:/,<FILEHANDLE>); print $result[3];

I am curious to know if there is a more perlish way of doing this(for e.g. in a one line)
I tried the following but it didnt work:
split(/:/,<FILEHANDLE>)[3]

Looking forward to seeing more perlish ways of doing this.
thanks,
narashima

Replies are listed 'Best First'.
Re: perlish way of splitting file records
by davorg (Chancellor) on Jun 01, 2006 at 15:46 UTC

    You were very close. You need a list slice.

    $result = (split /:/, <FILEHANDLE>)[3];
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: perlish way of splitting file records
by state-o-dis-array (Hermit) on Jun 01, 2006 at 15:54 UTC
    Is it always the fourth element you need or always the last? Consider:
    (split(/:/,<FILEHANDLE>))[-1]
    If you always want the last element.
Re: perlish way of splitting file records
by davido (Cardinal) on Jun 01, 2006 at 17:04 UTC

    For a short list like yours it doesn't really matter. But for a really big string with lots of elements, it's wasteful to create a big list (which is a copy of the string but split up) only to grab the last element. ...think along the lines of photocopying a book, and throwing away the entire copy except the last page.

    Here's a method that uses a regexp to find only the last element in the string:

    my $last_element; my $line = <FILEHANDLE>; if( $line =~ m/:([^:]*)\Z/ ) { $last_element = $1; }

    Dave

Re: perlish way of splitting file records
by bpphillips (Friar) on Jun 01, 2006 at 15:58 UTC
    you can also use an anonymous array to accomplish what you attempted in your second example:
    print [ split(/:/,<FILEHANDLE>) ]->[3]
    Oddly enough, to use a list slice there are some subtle parenthesis issues:
    # this works: print ((split /:/, <FILEHANDLE>)[3]); # doesn't work (note the missing outer parenthesis): print (split /:/, <FILEHANDLE>)[3];
    I'm guessing the second example has some ambiguity with taking the slice off the print or the split
    -- Brian

    Update: As pointed out below, an anonymous array is slower (by 39%) than a plain ol' list slice. Depending on the circumstances, however, it's very unlikely that this slowdown would ever be noticable (since on the box I tested, it was still able to perform 89,445 anonymous array creations and access per second).
      Yes, it's possible to use an anonymous array, but it's needlessly expensive when a list slice will do.