I think you might be missing one of the finer points of perl.
Functions can return completly different value depending on what
context they are called in. sort does not
always
return a list, it
usually does. If
sort is called
is a scalar context then the function returns undef.
It does not return a list if called in scalar context. So
the
scalar function is not placing the return value of sort
in scalar context it is placing the the actual function call
in scalar context.
Here is some code for demonstration:
This is what
Russ was refering to
$scalar = (5,10,15,20);
print $scalar, "\n";
Results:
20
This creates a function which will return different values
depending on the context that the function was called in:
sub get_list
{
# return a list if a list is wanted, else
# return the string
return wantarray ? (5,10,15,20) : "SCALAR CALL";
}
And to see this code in action:
$scalar = get_list();
print $scalar, "\n";
@array = get_list();
print join(" ", @array), "\n";
Results:
SCALAR CALL
5 10 15 20
And similarly:
print scalar(get_list()), "\n";
print join(" ", get_list()), "\n";
Results:
SCALAR CALL
5 10 15 20
Hopefully this helps.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.