[Za-pm] Passing values
Sean Carte
scarte at pan.uzulu.ac.za
Fri Jan 9 02:59:18 CST 2004
On Fri, 2004-01-09 at 10:22, Spike wrote:
> This seems to work too:-
>
> #!/usr/bin/perl
>
> use strict;
>
> my $num = 3;
>
> print "$num\n";
>
> double($num);
>
> print "$num\n"; # 6 expected
>
> #------------------------#
>
> sub double
> {
> $_[0] *= 2;
> }
>
>
>
> At 2004/01/09 10:04 AM, Sean Carte wrote:
> > First answer of the year!
At least I never said mine was the first *correct* answer of the year!
> >
> > $value = 3;
> > double(\$value); # pass a reference to $value
> > print "$value\n"; # 6 expected
> >
> > sub double {
> > my $ref = shift;
> > $value = $$ref; # dereference $ref
> > $value *= 2;
> > }
The above code only appears to work because it's updating $value in the
main namespace (is that the correct terminology?). It fails as soon as
you make $value local to the double subroutine (or change the variable
to something else):
my $value = 3;
double(\$value);
print "$value\n"; # 6 expected -- but not gotten
sub double {
my $ref = shift;
my $value = $$ref;
$value *= 2;
}
Surely there must be a way to do it via references ...?
--
Sean Carte <scarte at pan.uzulu.ac.za>
University of Zululand
______________________________________
Inflex - installed on mailserver for domain @pan.uzulu.ac.za
Queries to: postmaster at pan.uzulu.ac.za
More information about the Za-pm
mailing list