Re: Shift Question
- From: cdevers@xxxxxxxxx (Chris Devers)
- Date: Tue, 27 Sep 2005 19:32:40 -0400 (EDT)
On Tue, 27 Sep 2005, Dave Adams wrote:
> What is the purpose of the line "my $msg = shift;"?
In the context of subroutines, it copies the first scalar argument
passed to the routine to the variable $msg. If more than one argument
was passed, the others aren't touched by this statement -- as you note,
they are left alone in the @_ array.
Therefore, you sometimes see things like this:
sub multiply {
my $first_factor = shift;
my $second_factor = shift;
my $product = $first_factor * $second_factor;
return $product;
}
And other times see that abbreviated a bit, as:
sub multiply {
my ( $first_factor, $second_factor ) = @_;
my $product = $first_factor * $second_factor;
return $product;
}
They work about identically, but the first form gives you room to expand
the script in the future, by doing something like this:
my $first_factor = shift;
my $second_factor = shift or 1;
This lets you define a default value if the one noted wasn't specified.
More broadly, you can use that trick to handle unspecified arguments,
as:
my $msg = shift or "No message specified.";
Et cetera.
Also, don't bother with subroutine prototypes, e.g.
sub write_log($)
or
sub multiply($$)
as they just make the code harder to maintain, while doing little to
make the code clearer or more robust. The reasoning behind them is good,
but in practice they're more trouble than they're worth.
--
Chris Devers
?}?5Z¶?K4?!
- References:
- Shift Question
- From: Dave Adams
- Shift Question
- Prev by Date:
Re: Shift Question - Next by Date:
eval without warnings - Previous by thread:
Shift Question - Next by thread:
RE: Shift Question - Index(es):