After giving what I believed to be a complete answer yesterday, I realized that it still wasn't quite correct. It is true that subroutines return lists not arrays, but when called in scalar context they dont necessarily return the scalar value of that list.

The most obvious example of this is localtime() whose return values in scalar and list context have little to do with one another. Another example happens to be fetchrow_array()

From the DBI pod:

In a scalar context, fetchrow_array returns the value of the first field. An undef is returned if there are no more rows or if an error occurred. Since that undef can't be distinguished from an undef returned because the first field value was NULL, you should exercise some caution if you use fetchrow_array in a scalar context.
Using my logic, in scalar context we'd get the last field not the first.

The moral of the story is that the behavior of a subroutine in scalar context can't be determined from its list context return value.

Here are three subs that return the same values in list context, but behave differently in scalar context:

#!/usr/bin/perl -wT use strict; sub test1 { return @{[ qw(A B C) ]}; } sub test2 { return qw(A B C); } sub test3 { return wantarray ? qw(A B C) : 'I like jellybeans'; } print "List context\n", " test1: ", join(', ',test1()), "\n", " test2: ", join(', ',test2()), "\n", " test3: ", join(', ',test3()), "\n", "\nScalar context\n", " test1: ", scalar test1(), "\n", " test2: ", scalar test2(), "\n", " test3: ", scalar test3(), "\n"; =OUTPUT List context test1: A, B, C test2: A, B, C test3: A, B, C Scalar context test1: 3 test2: C test3: I like jellybeans

-Blake


In reply to Re4: MySQL / Perl Question by blakem
in thread MySQL / Perl Question by Anonymous Monk

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.