Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of (+) bareword with shift operator?

Tags:

perl

shift

I'm learning the intermediate perl.In that now I'm studying about the object references for class.In that they gave one package

{
    package Barn;

    sub new { bless [], shift }

    sub add { push @{ +shift }, shift }

    sub contents { @{ +shift } }

    sub DESTROY {
        my $self = shift;
        print "$self is being destroyed...\n";
        for ( $self->contents ) {
            print ' ', $_->name, " goes homeless.\n";
        }
    }
}

in this I can't understand the work of plus sign with shift operator. In text they said ,the plus sign is like bareword it would be interpreted as a soft reference: @{"shift"}

can you anybody clearly explain its work for using plus sign with shift operator?

like image 201
b.sabarathinam saba Avatar asked Jul 13 '16 12:07

b.sabarathinam saba


1 Answers

Without the plus sign, @{shift} is the same as the array @shift which doesn't call the shift operator at all. Adding the plus sign forces shift to be evaluated as an expression, so the shift operator is called

I would prefer to see @{ shift() }

Methods are normally written so that they extract the first parameter to $self, like this

sub new {
    my $class = shift;
    bless [ ], $class;
}

sub add {
    my $self = shift;
    push @$self, shift;
}

sub contents {
    my $self = shift;
    return @$self;
}
like image 195
Borodin Avatar answered Nov 15 '22 22:11

Borodin