Respected monks,

May be I am getting confused and/or doing something stupid, but please help me understand this.

I am trying to change the array content. So I wrote the following.

use strict; use warnings; my @arr = (1..10); sub test_this { print "Inside the sub, before the map \@arr: @arr\n"; print "Inside the sub, before the map \@\_ = @_\n"; @arr = map { 2 * $_ } @_; print "Inside the sub, after the map \@arr: @arr\n"; print "Inside the sub, after the map \@\_ = @_\n"; } print "Before calling the sub test_this \@arr: @arr\n"; &test_this(@arr); print "After calling the sub test_this \@arr: @arr\n";

But it seems to alter the @_ as well after the map. Here's the output.

pritesh@t430:~$ perl test.pl Before calling the sub test_this @arr: 1 2 3 4 5 6 7 8 9 10 Inside the sub, before the map @arr: 1 2 3 4 5 6 7 8 9 10 Inside the sub, before the map @_ = 1 2 3 4 5 6 7 8 9 10 Inside the sub, after the map @arr: 2 4 6 8 10 12 14 16 18 20 Inside the sub, after the map @_ = 2 4 6 8 10 12 14 16 18 20 After calling the sub test_this @arr: 2 4 6 8 10 12 14 16 18 20 pritesh@t430:~$

I was not expecting the @_ to change after the map and was expecting Inside the sub, after the map @_ =  1 2 3 4 5 6 7 8 9 10 but what shows is  Inside the sub, after the map @_ = 2 4 6 8 10 12 14 16 18 20

First I thought @_ is a copy of whatever I pass to the sub. But that's not the case.

What am I missing?


In reply to How come @_ gets changed here? by pritesh_ugrankar

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.