Evaluating an array in scalar context yields a count of how many elements exist in the array. Lists are different. People will jump in now and say there's no such thing as a list in scalar context. There isn't. So consider this code:

perl -e "print scalar( 'a', 'b', 'c', 'd' );"

The output is 'd'. perlop explains why:

Binary "," is the comma operator. In scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. This is just like C's comma operator.

In list context, it's just the list argument separator, and inserts both its arguments into the list.

The same is true for slices of an array, and lists generated with the qw// operator or through other basic means.

List functions can be defined to do all manner of different things in scalar context. split tells you the number of elements created, and splits into @_. Other functions do other things. That's dependant entirely on the function's code.

The diamond operator is defined to slurp a file in list context, or to return the next line (starting with the first) in scalar context.

So I guess that the answer is, if you got the last element you got documented behavior for some operators. If you're reading a single line from a filehandle, you'll get the first line the first time you read from the filehandle. That too is expected, and documented in perlop. If you got something else, we'll need to see more information to explain where that behavior is documented.


Dave


In reply to Re: Reading files in scalar context with <> operator by davido
in thread Reading files in scalar context with <> operator by senőr_biggles

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.