Can someone tell me what
shift if(@_)
means in perl?
and so what would
sub id {
my $self = shift;
$self->{ID} = shift if @_;
return $self->{ID};
}
mean? Thanks.
That is a handrolled accessor/mutator for an object
print $obj->id; # Accessor form
$obj->id(NEW_VAL); # Mutator form
It is functionally equivalent to:
sub id {
my $self = shift;
if (@_) { # If called with additional parameters, set the value:
$self->{ID} = shift(@_);
}
return $self->{ID};
}
In a sub, shift without argument uses @_ array.
So
$self->{ID} = shift if @_;
is equal to
$self->{ID} = shift(@_) if @_;
(remove leftmost element from @_ array and assign it to $self->{ID})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With