princepawn has asked for the wisdom of the Perl Monks concerning the following question:

Questions:
  1. Why must I preface my call to z() with an ampersand? I didnt have to do that for my calls to x() or y()...
  2. Is there some reason that the call to y() does not bind scalars used as its arguments?
  3. Where should I have looked in the Perl documentation for an answer to my questions? I looked in perlref and perlsub but no luck.
use strict; sub x { ($_[0],$_[1],$_[2])=qw(fee fi fo) } sub y { @_ = qw(one two three) } sub z { ($_[1],$_[2],$_[3]) = @{$_[0]} } my ($x,$y,$z); x($x,$y,$z); print "$x, $y, $z", $/; y($x,$y,$z); print "$x, $y, $z", $/; &z( [ 77,44,232], $x, $y, $z); print "$x, $y, $z", $/;

Replies are listed 'Best First'.
Re: Using @_ as an lvalue
by japhy (Canon) on Mar 23, 2001 at 21:11 UTC
    You should NOT name a function y (or tr, or m, or q, ...). What's happening is your function y() is never getting called. Your code is the same as:
    use strict; sub x { ($_[0],$_[1],$_[2])=qw(fee fi fo) } sub y { @_ = qw(one two three) } sub z { ($_[1],$_[2],$_[3]) = @{$_[0]} } my ($x,$y,$z); x($x,$y,$z); print "$x, $y, $z", $/; tr!$x,$y,$z! print "$x, $y, $z", $/! &z( [ 77,44,232], $x, $y, $z); print "$x, $y, $z", $/;
    That is why you have to preface z() with an &, because the code looks like:
    tr/abc/def/ &function(); # which is really tr/abc/def/ & function();
    But even so, @_ is not binded specially. The elements in it are, but not the array as a whole. Assigning to the array as a whole breaks any bond.

    japhy -- Perl and Regex Hacker
    A reply falls below the community's threshold of quality. You may see it by logging in.