Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, shift if(@_)

Tags:

perl

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.

like image 840
Thaddius Avatar asked Mar 24 '26 05:03

Thaddius


2 Answers

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};
}
like image 194
Miller Avatar answered Mar 26 '26 18:03

Miller


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})

like image 42
mpapec Avatar answered Mar 26 '26 19:03

mpapec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!