Context in Perl
In Perl, you can store a number or a string (or a reference or a regular expression) in a scalar variable, and you can store a collection of such scalars in a list.
Scalar variables are written starting with a $, and list variable names starting with an @. You can perform operations on a list as a whole using standard operators - known as "list context". If you do something that really isn't sensible on a list, then Perl will do it in scalar context instead, where it takes the length of the list and uses that.
If you write a list within double quotes, that's in effect a third context - "double quote context" - and it expands the list with a space between each element.
Here's an example:
@sarnie = ("Cheese","Tomato","Marmite","Onion");
@pizza = @sarnie; # list CONTEXT
$lasagne = @sarnie; # scalar CONTEXT - the length of a list
$pie = "@sarnie"; # double quote CONTEXT - string
print @sarnie,"\n";
print @pizza,"\n";
print $lasagne,"\n";
print $#sarnie,"\n"; # Top index number (== length of list -1)
print $pie,"\n";
print "@sarnie\n"; # Double quote context again
($main,$trimming) = @sarnie; # ( and ) force list context
($another) = @sarnie; # list context
$yetanother = @sarnie; # scalar context
print "That's a $main sarnie with a bit of $trimming\n";
print "Looking at $another and $yetanother\n";
Here's what you'll see if you run that:
[localhost:~/pfeb] graham% perl llold
CheeseTomatoMarmiteOnion << List context
CheeseTomatoMarmiteOnion << List context
4 << Scalar Context
3
Cheese Tomato Marmite Onion << Double Quote Context
Cheese Tomato Marmite Onion << Double Quote Context
That's a Cheese sarnie with a bit of Tomato
Looking at Cheese and 4
[localhost:~/pfeb] graham%
See also
Perl Lists
Please note that articles in this section of our
web site were current and correct to the best of our ability when published,
but by the nature of our business may go out of date quite quickly. The
quoting of a price, contract term or any other information in this area of
our website is NOT an offer to supply now on those terms - please check
back via
our main web site
Perl - Lists [28] - ()
[140] - ()
[230] - ()
[240] - ()
[355] - ()
[463] - ()
[560] - ()
[622] - ()
[762] - ()
[773] - ()
[928] - ()
[968] - ()
[1304] - ()
[1316] - ()
[1703] - ()
[1828] - ()
[1917] - ()
[1918] - ()
[2067] - ()
[2226] - ()
[2295] - ()
[2484] - ()
[2813] - ()
[2833] - ()
[2996] - ()
[3400] - ()
[3548] - ()
[3669] - ()
[3870] - ()
[3906] - ()
[3939] - ()
[4609] - ()
resource index - Perl
Solutions centre home page
You'll find shorter technical items at
The Horse's Mouth and
delegate's questions answered at
the
Opentalk forum.
At Well House Consultants, we provide
training courses on
subjects such as Ruby, Lua, Perl, Python, Linux, C, C++,
Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer)
many questions, and answers to those which are of general
interest are published in this area of our site.