Context is Everything

March 1, 2001, 12:00 AM —  ITworld — 

When writing Perl programs, you really must be aware of the two main
contexts: Scalar and List. Things can behave differently when evaluated
in one or the other context.

We'll employ probably the most well know example, assigning an array:

my @list = @array; # @array is in list context
my $scalar = @array; # @array is in scalar context

The first case above assigns @array to another array, providing list
context, so it returns the list of its contents. The second example
assigns @array to a scalar variable, thus putting it in scalar context.
An array in scalar context returns the size of the array. Now, one
twist on the second example places @array in list context.

my ($scalar) = @array; # @array is in list context;

The parentheses around the scalar indicates a list of scalars (in this
case, a list of length one) on the assignment's left side, thus putting
the @array in list context. Now @array returns the list of its contents
and the first element is assigned to $scalar (the rest of the list
returned by the array is ignored).

Another example uses the keys() function of a hash. In list context, it
returns the given hash's list of keys; but in scalar context, it
returns the number of keys in the hash. A hash itself in list context
returns the full list of key value pairs (in the same sequence as the
keys() function returns the keys). However, in scalar context it
returns information about the underlying hash structure.

my %hash = (one => 1, two => 2);
print %hash, "\n"; # prints: one1two2
print scalar %hash, "\n"; # prints: 2/8

The print() function provides a list context (the function expects to
receive a list of arguments). The scalar() function can be used to
explicitly evaluate an expression in a scalar context (as we do in the
last example above). That final version tells us that our hash
currently has 8 buckets allocated and that two are being used.

Now we've already seen that functions can return different results
depending on context with the keys() function, so let's look at the
localtime() function (see: perldoc -f localtime). Operators can also
act context dependently, as with the match operator m// (and that
behaviour is also modified by the /g modifier). The x operator (string
replication) works differently if its left side is a scalar or a list.

Functions themselves may also supply context to their arguments. Take,
for example, the join() function. It first expects a scalar value as an
argument holding the string to be used as the join separator. If you
thought you could just put all the arguments to join into a single
array and pass that, then you wouldn't get the results you wanted.

my @args = (":", 1,2,3);
my $str = join @args;
print $str; # $str is empty

Above, the join() function expected a scalar as the first argument and
evaluated the @args array in a scalar context to get the separator
character (in this case the size of the array which is 4). No arguments
followed to join together.

If a function or operator behaves differently depending on scalar or
list context, it is documented in the relevant documentation pages (see
the perlfunc and perlop manpages).

Next Week: More on Context (boolean and operator contexts)

» posted by ITworld staff

ITworld

Sign up for ITworld's Daily newsletter
Follow ITworld on Twitter @IT_world

I like it!
Post a comment
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
peer-to-peer

Esther Schindler
If the comments are ugly, the code is ugly

claird
SVG a graphics format for 21st century

pasmith
Take Chrome OS for a test spin

Sandra Henry-Stocker
Solaris Tip: Have Your Files Changed Since Installation?

sjvn
64-bits of protection?

jfruh
Android fragments vs. the iPhone monolith

mikelgan
What Gizmodo missed about the Pro WX Wireless USB disk drive

 

Where Google Chrome security fails: the password
I heard mention that the Chrome OS will have some sort of encryption available a la bitlocker. If it's possible to encrypt personal data using another password or key, then it may have potential for very secure data.... And Ubuntu has an 'encrypt home directory' option, perhaps google should follow suit.
- Dann

Join the conversation here

The Daily Tip

The Daily TipQuick, practical advice for IT pros. Made fresh daily.

Hot tips:

Want to cash in on your IT savvy? Send your tip to tips@itworld.com. If we post it, we'll send you a $25 Amazon e-gift card.

Newsletters

Subscribe to ITWORLD TODAY and receive the latest IT news and analysis.

I would like to receive offers via email from ITworld partners.
By clicking submit you agree to the terms and conditions outlined in ITworld's privacy policy.
Featured Sponsor

AISO founders envisioned a Web hosting company that was environmentally friendly. While the company employed energy-efficient innovations like solar panels, its infrastructure produced unacceptable power and cooling requirements. Find out how AISO leveraged AMD technology to overcome their challenge in this case study white paper.

In this whitepaper, Scalar explores the opportunity to change the landscape with respect to mission critical databases built around Oracle. Leveraging technologies such as Linux, high-end commodity processing power and Oracle RAC technology to architect, design, build and maintain database infrastructure that delivers maximum availability, reliability and performance at a fraction of traditional cost.

On a typical day, weather.com, the Web site for The Weather Channel in Atlanta, serves up between 15 million and 20 million page views. But in September 2004, when back-to-back hurricanes ransacked Florida, the peak traffic on one day more than tripled: over 70 million page views by more than 7 million unique visitors. Read the full success story now.

Marketplace