> Hi all, I'm having a look in to object oriented perl.  Can anyone tell me 
> what the difference between @_ and shift is?  

One is a variable, one is function/operator ;-)....

As far as I know there is no 
> difference except "shift" removes the parameter from the @_ array so
if you 
> were to "shift" all parameters passed to a function nothing would be 
> containted in @_   is this correct?
> 

@_ is just a special Perl variable, it so happens that it is what is
used to store the arguments to a subroutine temporarily (it has other
uses, see perldoc perlvar).  It also happens that the first argument to
a subroutine acting like a method is always the object/class that the
method is invoked on. C<shift> is just a function that removes the
first/top element of an array, any array, in OOP or not. 

This happens to make things very convenient, aka in most methods you
will want to remove the instance/class from the argument list to get the
 actual argument list back, and shift by itself will default to use @_.
So essentially you are left with some syntactic sugar to make life easier.

So,

my $self = shift;

Just says to grab the instance from @_ (by default), store it in $self,
and restore the arg list to what the user actually passed.  You don't
*have* to do it, but it is very convenient.

> I'm asking because I'm a little confused about using it.  Why can't I do 
> this:
> 
> #######################################
> sub nickname {
>         my $self = shift;
>         return $self->{NICK};
> }

No reason you can't.  Provided you have already set $self->{NICK} or
don't mind getting an undefined value. 


> #######################################
> 
> But I can do this:
> 
> #######################################
> sub nickname {
>         my $self = shift;
>       if (@_) { $self->{NICK} = shift
>       }
>         return $self->{NICK};
>     }
> #######################################
> 

Only difference here is that you set $self->{NICK} in the event that an
argument was passed, aka after shift'ing there is still an argument in
@_ (namely the value you want to set NICK to).

Additional suggested reading:

perldoc perlboot
perldoc perltoot
perldoc perltooc

http://danconia.org

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to