Perl Contexts: Void, Scalar, List, and Boolean

   

There are three main lvalue (left-hand value) contexts in Perl; void context, scalar context, and list context. They typically operate when subroutines are called or when an lvalue assignment is made:

 localtime(  );               #  Step 1:  Void context, nothing returned    $this_time = localtime(  );  #  Step 2:  Scalar context, scalar returned print "$this_time \n";    @array_time = localtime(  ); #  Step 3:  Array (or list) context, array print "@array_time \n";    #         returned. 

This code produces:

 Wed Mar  6 22:40:40 2002 40 40 22 6 2 102 3 64 0 

Let's look at the three contexts illustrated here.

Void

In void context the localtime( ) function fails to return anything. Otherwise Perl uses a built-in wantarray operator in the background to return whether the function is supposed to return a scalar value or an array list.

Scalar

When the lvalue is a scalar, as with $this_time , we know a scalar is required, so localtime( ) supplies us with a single string of information:

 Wed Mar  6 22:40:40 2002 

List

In our last code line, wantarray tells us that an array is required in list context, so localtime( ) gives us an array of different time-based variables supplying seconds, minutes, hours, day of the month, month, number of years since 1900, the weekday, the day of the year, and a daylight savings time flag:

 40 40 22 6 2 102 3 64 0 

Boolean

There is no boolean variable type in Perl, just Boolean context. In essence, if a scalar is a string and it is either empty "", or set to "0", then it is interpreted as false. If it is numeric and 0 or 0.0, it is interpreted as false. Absolutely everything else, except the special undef value, is interpreted as true. (This can go against the grain for shell programmers, where 0 is true and everything else is false, but is natural for C programmers from the ol' country.)

   


Perl for Oracle DBAs
Perl for Oracle Dbas
ISBN: 0596002106
EAN: 2147483647
Year: 2002
Pages: 137

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net