-
When perl is expecting a list, how do you force scalar
context? Provide a sample.
If a list variable is used as a scalar, then the result is the number of elements
in the list (or one more than the highest index of the list if the elements were
assigned non-consecutively). Using the word "scalar" in front of the list forces
it to be interpreted as a scalar as shown below.
(Learning Perl, p. 51)
@group = qw( Peter Paul Mary);
print "The highest index is $#group.\n";
print "The group members are @group.\n";
print "The group has ", scalar @group, " members.\n";
$group2[0]="John";
$group2[2]="Michelle";
$group2[4]="Cass";
$group2[6]="Denny";
print "The highest index is $#group2.\n";
print "The group members are @group2.\n";
print "The group has ", scalar @group2, " members.\n";
Result:
-
What is perl's favorite default when omitting a control
variable from a loop? Show an example of its use:
In the example below the statement foreach (3..20) sets
up a for loop that goes from 3 up to and including
20. There is an implied counting variable. If the programmer
wants to use the implied counter explicitly, he or she can
use the default variable $_.
(Learning Perl, p. 47)
$fib1 = 1;
$fib2 = 1;
print "1.\t$fib1\n";
print "2.\t$fib2\n";
foreach (3..20)
{
($fib1, $fib2) = ($fib2, $fib1+$fib2);
print "$_.\t$fib2\n";
}
Result:
-
How do you get the last element index of an array?
Placing a dollar sign ($) followed by a pound sign (#) in
front of the name of an array provides the highest index of
the array. (Learning Perl, p. 40). For example,
the lines
@group = qw( Peter Paul Mary);
print "The highest index is $#group.\n";
yield the output: The highest index is 2.
-
Which perl function is used to examine every element of
a hash?
The each function uses a hash's internal iterator to step
through and return key/value pairs -- one pair at a time.
For example
while( ($key, $value) = each %ENV)
{
print "$key => $value\n";
}
prints out the contents of the environment hash.