in reply to A list returns its last, an array returns its weight

Lists and arrays do this in the rest of nature
print scalar qw( foo bar baz ),$/; print scalar @{[qw( foo bar baz )]}, $/; __output__ baz 3
And rather interestingly (to me at least) arrays aren't flattened in lists when evaluated in a scalar context e.g
print scalar +(undef,@INC),$/; __output__ 10

HTH

_________
broquaint

Replies are listed 'Best First'.
Re: Re: A list returns its last, an array returns its weight ...
by jdporter (Paladin) on Nov 12, 2002 at 20:39 UTC
    The lesson, of course, is that context propagates. It propagates into subroutine calls, down to the point where the sub would return; and it propagates into lists of all kinds.
    @a = qw( x y ); # scalar(@a) == 2 @b = qw( foo bar quux ); print $b[ 0, @a ]; # prints "quux"
    (For those of you who are more familiar with CSS, it could be said that context "cascades". :-)

    jdporter
    ...porque es dificil estar guapo y blanco.

      Hi,

      Indeed, and this is where wantarray comes in.


      ---------------------------
      Dr. Mark Ceulemans
      Senior Consultant
      IT Masters, Belgium

        Yeah. But the need for wantarray is, in my experience, rare indeed. Almost always, I'm happy to let the normal context handling do its thing. For example:
        # let array handle context. # list of items in list context, count of items in scalar. sub find_things { my( $storage, $criteria ) = @_; my @things = $storage->lookup( $criteria ); @things } # let grep handle context. # list of items in list context, count of items in scalar. sub matching_things { my( $storage, $pat ) = @_; grep /$pat/, $storage->things() }
        That's not to say that wantarray is never useful. For example, if building a result list is expensive, you can use wantarray to avoid that cost in scalar context.
        # list of items in list context, first item in scalar. sub matching_things { my( $input_iter, $pat ) = @_; my @things; while ( <$input_iter> ) { /$pat/ or next; wantarray or return $_; push @things, $_; } @things }

        jdporter
        ...porque es dificil estar guapo y blanco.