[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index][Thread Index][Top&Search][Original]
Re: Localization method of $1
On Jan 15, Peter Scott said:
> sub pref { \$_[0], " = ", shift || '(undef)', "\n" }
>
> $_ = "abc";
> print "Before setting: ", pref $1;
> s/(ab)/bar($1)/e;
> print "After s///: ", pref $1;
>
> sub bar {
> $_[0] =~ /(b)/;
> print "Inside /e sub: ", pref $1;
> print "Original \$1 now: ", pref $_[0];
> # Note: attempt to assign to $_[0] here generates
> # "Modification of a read-only value"
> }
That's because $_[0] is /really, truly/ $1.
@_ = ("new thing") ;
Will not affect $1. Assigning to a specific index of @_ will modify the
variable that was passed to the function in that position (see the code
below).
Elements of @_ are aliases to the actual variables. If, however, you
assign to @_ by a means other than specific indices, this bond is broken.
$var = 1;
foo($var);
sub foo {
print "$_[0], $var\n";
$var = 2;
print "$_[0], $var\n";
$_[0] = 3;
print "$_[0], $var\n";
@_ = (4);
print "$_[0], $var\n";
$_[0] = 5;
print "$_[0], $var\n";
$var = 6;
print "$_[0], $var\n";
}
1, 1
2, 2
3, 3
4, 3
5, 3
5, 6
This is with Perl 5.005_02, just so you know.
--
MIDN 4/C PINYAN, USNR, NROTCURPI http://www.pobox.com/~japhy/
jeff pinyan: japhy@pobox.com perl stuff: japhy+perl@pobox.com
"The Art of Perl" http://www.pobox.com/~japhy/book/
CPAN ID: PINYAN http://www.perl.com/CPAN/authors/id/P/PI/PINYAN/
PerlMonth - An Online Perl Magazine http://www.perlmonth.com/
- Follow-Ups from:
-
Peter Scott <Peter@PSDT.com>
- References to:
-
Peter Scott <Peter@PSDT.com>
[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index][Thread Index][Top&Search][Original]