The following function calculates whether a year is a leap year.
#!/usr/bin/perl
$my_year = 2000;
if ( is_leap_year( $my_year ) )
{ # Call function with an argument
print "$my_year is a leap year\n";
}
else
{
print "$my_year is not a leap year";
}
sub is_leap_year { # Function definition
my $year = shift(@_); # Shift off the year from
# the parameter list, @_
return ((($year % 4 == 0) &;& ($year % 100 != 0)) ||
($year % 400 == 0)) ? 1 : 0; # What is returned from the function
}
In the above example, my $ year = 2000; this code has a key word shift, which provides relevant explanations.
When reading other people's perll code, it is often found that the header is"
$ Variable = shift ;"
First, let's look at the explanation of shift () in perldoc.
perldoc -f shift
shift ARRAYshift Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the @_ array within the lexical scope of subroutines and formats, and the @ARGV array outside a subroutine and also within the lexical scopes established by the "eval STRING", "BEGIN {}", "INIT {}", "CHECK {}", "UNITCHECK {}" and "END {}" constructs. See also "unshift", "push", and "pop". "shift" and "unshift" do the same thing to the left end of an array that "pop" and "push" do to the right end.
Shift off (can be understood as removing) The first variable in the array and returns
If no parameter is specified in Perl by default, the default parameter is obtained based on the context.
So when we define such a pl File
1.pl
$host = shift;
Obviously, the parameter of the shift operation is @ _, that is, @ argv.
This statement directly retrieves the first parameter passed by the user.
In short, when shift does not have an array as the parameter, It is the default parameter "Move.
This default method is often used in Perl.