[EMAIL PROTECTED] am Dienstag, 4. Juli 2006 19:17:
> I have a subroutine that, amongst other things, chops a scalar variable,
> $dir, passed to it as an argument.  The problem is that I need $dir intact
> (ie unchopped) after calling said subroutine, but it has been altered by
> the chop.  I can't figure out how to pass the value (or more precisely, a
> copy of the value) of $dir to subroutine so that it's operations do not
> alter what $dir originally contained.  I've read Mr. Wall's Camelbook and
> saw lots of info on hard, soft, and symbolic references, but nothing (that
> I could understand) about passing a copy of variable to a subroutine and
> not the variable itself.

In addition to Shawn's and Aaron's answer:

---begin---
#!/usr/bin/perl
use strict;
use warnings;

my $dir="/some/dir\n";

sub handle_a_copy {
        my $copy=shift;
        chomp $copy;
        print "a) value in handle_a_copy: <$copy>\n";
}

sub handle_original {
        chomp $_[0];
        print "b) value in handle_original: <$_[0]>\n";
}

sub handle_a_ref {
        my $ref=shift;
        chomp $$ref;
        print "c) value in handle_a_ref: <$$ref>\n";
}

sub handle_localized { # generally not recommended
        local $_[0]=$_[0];
        chomp $_[0];
        print "d) value in handle_localized: <$_[0]>\n";
}

print "<$dir>\n";
handle_a_copy ($dir);
print "<$dir>\n";
handle_original ($dir);
print "<$dir>\n";
$dir="/some/dir\n"; # reset
handle_a_ref(\$dir);
print "<$dir>\n";
$dir="/some/dir\n"; # reset
handle_localized ($dir);
print "<$dir>\n";
---end---


# output:

</some/dir
>
a) value in handle_a_copy: </some/dir>
</some/dir
>
b) value in handle_original: </some/dir>
</some/dir>
c) value in handle_a_ref: </some/dir>
</some/dir>
d) value in handle_localized: </some/dir>
</some/dir
>


# short explanation:

a) shifts from the @_ into $copy, and $copy is an independent copy of $dir 
b) accesses the scalar value in @_ directly, that is, the original $dir in it.
c) a reference to the original $dir is passed, the sub handles the 
dereferenced original.
d) the sub localizes the original $dir, that is, remembers the original 
value, "overwrites" it with a copy (valid in the scope of the sub and the 
subs that would be called from it), and restores the original value when done 
(when the program flow leaves the subroutine scope)

As you can see, both the way of passing the argument and the way a sub handles 
the passed argument can have an influence on whether the original value is 
kept or not.

To be sure that the original value is not changed, you have to copy it before 
(or while) passing it to a subroutine. From the sub definition alone you 
cannot be sure if it is changed or not, and have to consult the 
documentation.

Check out

perldoc perlsub

Hope this helps,

Dani

-- 
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