I’ve just started learning perl and I am am confused by this exercise (from Learning Perl Chapter 4).
At the beginning of the greet() subroutine, I am trying to assign the argument $_ to my $name (my $name = $_) variable but it doesn’t work. The book says to use “my name = shift;” but I don’t understand why. shift is used to remove a value from an array and my argument is not an array as far as I can tell, it’s a string inside a scalar!
Could anyone explain what I’m not understanding?
Thanks! Here is the entirety of the code.
use 5.012;
use warnings;
use utf8;
sub greet {
my $name = $_;
state $last_person ;
if (defined $last_person ) {
print "Hi $name! $last_person is also here!\n";
} else {
print "Hi $name! You are the first one here!\n";
}
$last_person = $name;
}
greet( 'Fred' );
greet( 'Barney' );
greet( 'Wilma' );
greet( 'Betty' );
In chapter 4 of Learning Perl (6th edition) there’s a section called Arguments. There it states the following:
(Learning Perl, 6th Edition, Chapter 4)
So you’re probably mistaken in using
$_, when you should either be usingmy $name = $_[0];, ormy $name = shift @_;. As a convenience, when you’re inside of a subroutine,shiftdefaults to shifting off of@_if you provide no explicit argument, so the common idiom is to saymy $name = shift;.For those in need of another resource, perldoc perlintro also has a good (and appropriately brief) explanation of passing parameters to subroutines and accessing them via
@_orshift.Here’s a brief snippet from
perlintro: