in reply to Empty List miracle(1)

Only arrays return the number of elements in scalar context, lists don't.

Some people say that lists don't exist in scalar context (and I disagree, but that's really a pointless discussion), but if we assume they do exist, then the default behaviour of a list is scalar context is to return its last element:

print scalar(1, 2, 3);

prrint the 3.

(Update) and the last element of an empty list is not defined, which is why you get the warning.

Replies are listed 'Best First'.
Re^2: Empty List miracle(1)
by ikegami (Patriarch) on Apr 30, 2010 at 14:19 UTC

    There's no default.

    If you say there's such a thing as a list in scalar context, it's because you're talking about list literals or the list operator. If so, the only behaviour for a list in scalar context is to return its last element after evaluating it in scalar context. undef is returned for empty lists.

    # List literal in list context >perl -E"sub c { @a=qw(d e f g); @a } say('a', 'b', c())" abdefg # List literal in scalar context >perl -E"sub c { @a=qw(d e f g); @a } say(scalar('a', 'b', 'c'))" c # List literal in scalar context >perl -E"sub c { @a=qw(d e f g); @a } say(scalar('a', 'b', c()))" 4 # scalar(@a)
Re^2: Empty List miracle(1)
by chromatic (Archbishop) on Apr 29, 2010 at 23:37 UTC
    ... the default behaviour of a list is scalar context is to return its last element...

    ... depending on associativity and precedence and arity and the presence of any prototypes in the surrounding expression which may change any of the former, so the choice of the word "default" is, at best, misleading.

      So what would be a better phrasing, in your opinion?
      Perl 6 - links to (nearly) everything that is Perl 6.

        I don't think there is a good way to explain the default behavior of a list in scalar context, because there are too many ways to create lists in Perl and too many ways to enforce scalar context.

        What does a list do in scalar context provided by scalar assignment?

        What does a list do in scalar context provided by the scalar operator?

        What does a list do in scalar context provided by any other infix operator?

        What does a list do in scalar context provided by the prototype of an operator?

        I might be missing some (hash key?).