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

assuming @fields contains qw/one two three four/, why doesn't below work? (if I wanted to extract two and four?
@yahoo = $fields[1,3];

Replies are listed 'Best First'.
Re: accessing multiple items from array
by kyle (Abbot) on Sep 11, 2007 at 03:22 UTC
Re: accessing multiple items from array
by ikegami (Patriarch) on Sep 11, 2007 at 05:03 UTC

    @array[EXPR] is a slice. EXPR will be evaluated in list context, resulting in a mulitple number, resulting in mulitple elements being returned.

    $array[EXPR] is just simple indexing and not a slice. EXPR will be evaluated in scalar context, resulting in a single number, resulting in a single element being returned.

    Note that in scalar context, the comma is the comma operator, a binary operator that evaluates both operands and returns the right operand. That means that 1,3 returns 3 in scalar context.

Re: accessing multiple items from array
by quester (Vicar) on Sep 11, 2007 at 05:45 UTC
    Also, if you had turned on warnings, you would have been tipped off by the message "Multidimensional syntax $fields[1,3] not supported at line...".

    YMMV, but I find it's a lot faster to add the perl -w switch to one-liners than to debug them without it. I'll admit that I don't always use strict until my scripts get to be, oh, five or six lines long. Mea culpa.

    Chants softly

    use strict;
    use warnings;
    
    use strict;
    use warnings;
    
    use strict;
    use warnings;
    
    ...