in reply to @array[1] is valid??

As other have explained, it's a one element slice. Unfortunally, if you use it like this, Perl will issue a warning. I don't think it's right that Perl should give this warning; why should a one element slice trigger a warning when two, three, four, ..., or even a zero element slice don't? Furthermore, in most cases @foo 1 is used in rvalue context, where it won't matter anyway. The only place where it might go wrong, is where you use @foo 1 in lvalue context, and the RHS of the assignment returns different things in list and scalar context.

But that's a rare case. In a more common case, which more often goes wrong is my ($foo) vs my $foo. But Perl doesn't warn there.

And considering that in perl6, @foo 1 is the right way to address a single element (what's perl6 syntax for a one element slice?), I think that warning ought to removed from Perl.

I've once send that in as a wish to p5p, but it was ignored.

Abigail

Replies are listed 'Best First'.
Re^2: @array[1] is valid??
by Aristotle (Chancellor) on Aug 05, 2003 at 14:19 UTC
    Is there any time when an explicit single element list (as opposed to one where the slice is determined dynamically) ever makes sense? I can't think of any. There are many occasions where my ($foo) makes sense, however. Assuming that warnings are meant to aid the user and do not have to be orthogonal, this warning makes sense IMHO.

    Makeshifts last the longest.

      #!/usr/bin/perl use strict; no warnings; my (@firstkey, @numberofkeys); my @list = qw /foo housekey blah carkey baz monkey/; @firstkey [0] = grep {/key$/} @list; $numberofkeys [0] = grep {/key$/} @list; print "@firstkey\n"; print "@numberofkeys\n"; __END__ housekey 3

      And yes, there are a million different ways to write this code, but that's not the point.

      But I can't think of a case where using @array [0] in non-lvalue context could return something else than $array [0].

      Abigail

        That seems contrived. I can't imagine a single case where I'd do it this way, rather than
        my ($firstkey) = grep {/key$/} @list; my $numberofkeys = grep {/key$/} @list;

        I could see that usage if you were doing @firstkey[$of_list_nr_x], but then that doesn't emit a warning.

        Unless your point is that the warning breaks orthogonality, which is not an argument I care about here.

        Makeshifts last the longest.