Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: difficulty in understanding use of @_ and shift in a subroutine

by Loops (Curate)
on Oct 27, 2014 at 06:13 UTC ( [id://1105083]=note: print w/replies, xml ) Need Help??


in reply to difficulty in understanding use of @_ and shift in a subroutine

Hi masood91, welcome to the monastery.

You're free to use whichever form you like to process arguments. There may be efficiency gains one way or the other, but usually that isn't overly important. More often, it just is more clear in the shift form.

You should be careful though, because your suggestion of using "my $a=@_" wont actually work as you hope. Instead $a will be set to the number of values contained in @_. What you'd want instead is:

my ($a) = @_;  # force list context in the assignment

or

my $a = $_[0];  # set $a to the first parameter passed

Here's an example where you might prefer to use shift:

abc('hello', 3271, 33, 44); sub abc{ my $a = shift; print "$a $_\n" for (@_) }

Replies are listed 'Best First'.
Re^2: difficulty in understanding use of @_ and shift in a subroutine
by masood91 (Novice) on Oct 27, 2014 at 06:19 UTC
    Right.. Thanks for clearing my confusion. I have been searching this for hours, and at last I remember why not search a Perl forum, if there is any. S here I am. Thanks for your reply and welcoming me. Hope I will learn a lot here. My ultimate goal is web development using Perl. I have started reading "Beginning Perl" book. Suggest me some for web development if you know :) Thanks a lot
      for a quick lesson u could also read man perlsub or perldoc perlsub.
      all the best for your perl journey .it will rock!
      Do not wait to strike when the iron is hot! Make it hot by striking - WB Yeats

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1105083]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-25 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found