Re: newbie baffled by de/referencing with subroutines
- From: Tad McClellan <tadmc@xxxxxxxxxxxxxx>
- Date: Sun, 10 Apr 2005 17:59:44 -0500
Jessica <konradj@xxxxxxxxxxxxxx> wrote:
> I created an elaborate array (my @uniqueParsed) inside a subroutine
> and I want to use data from that array after the sub is finished. I
> declared a reference inside the sub:
>
> my $uniqueParsed_r = \@uniqueParsed;
>
> then tried to print the data outside the sub by this dereference:
>
> print "dereferenced array is @$uniqueParsed_r \n";
>
> but nothing was returned (i.e., @$uniqueParsed_r is empty). By the
> way, if I put the print statement inside the sub, the dereferenced
> array prints correctly.
You should always enable strict and warnings when developing Perl code!
> What's wrong with my reference and/or dereference,
There is nothing wrong with either your reference nor your dereference.
There is something wrong with your variable scoping.
(I am forced to guess that that is what it is, because you did
not include a short and complete program that I can run. Have
you seen the Posting Guidelines that are posted here frequently?
)
> and how do I fix it?
Don't declare a lexical variable that will cease to exist as
soon as the subroutine returns, instead return a reference
to the elaborate array.
sub nameless_sub {
my @uniqueParsed;
# populate the array...
return \@uniqueParsed;
}
my $uP = nameless_sub();
print "dereferenced array is @$uP\n";
--
Tad McClellan SGML consulting
tadmc@xxxxxxxxxxxxxx Perl programming
Fort Worth, Texas
.
- References:
- newbie baffled by de/referencing with subroutines
- From: Jessica
- newbie baffled by de/referencing with subroutines
- Prev by Date: Re: if(wantarray){...}else{...}
- Next by Date: UTF-8 in regexp with 5.8.1
- Previous by thread: Re: newbie baffled by de/referencing with subroutines
- Next by thread: if(wantarray){...}else{...}
- Index(es):
Relevant Pages
|