Hello masood91, and welcome to the Monastery!

In Perl, arguments are passed into subroutines by reference (as opposed to a language like C, in which arguments are passed by value). The special variable @_ contains aliases to the arguments passed in, so you can use them directly:

sub abc { $_[0] = 42; }

but that changes the variables outside of the subroutine. For example, if the above were called as follows:

my $x = 17; abc($x);

then after the subroutine call $x would contain 42. Since this is usually not what you want, it is standard practice to simulate pass-by-value by copying the arguments as the first statement in the subroutine:

sub abc { my ($x, $y, $z) = @_; }

or (less commonly):

sub abc { my @args = @_; }

(Note that @_ is an array variable.) To remove the first element from an array and get its value, Perl provides shift:

my $num = shift @array;

After this operation the first element in @array has been removed and stored in the scalar variable $num. Now, within a subroutine, if shift is used without an argument then it automatically applies to @_. Hence, another common idiom is:

sub abc { my $x = shift; my $y = shift; my $z = shift; }

which does the same as:

sub abc { my ($x, $y, $z) = @_; }

except that with shift the elements are also removed from the @_ array.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: difficulty in understanding use of @_ and shift in a subroutine by Athanasius
in thread difficulty in understanding use of @_ and shift in a subroutine by masood91

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.