Re: newbie baffled by de/referencing with subroutines



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
.



Relevant Pages

  • Re: VB-101: Passing Arrays ByVal vs ByRef
    ... My questions was why the 2nd part of the sub did not change the changes the ... > changes to the array pass it byref. ... > ' new reference ... > ' allocate secondArray and copy its reference ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Another Dereference Post by me
    ... > statement near the bottom does not dereference the values. ... > Then what I really want is to sort by the 5th column that looks ... you're creating an anonymous array reference. ... So now you've created a reference to an array containing ...
    (comp.lang.perl.misc)
  • Re: How to pass function name as a parameter?
    ... > Public Sub operator_index(ByVal index As Integer, ... I'm not sure what you mean by return type of reference, ... want to do is have an object that acts like an array, ... overlook what you can do with Properties, which don't really have a C++ ...
    (microsoft.public.vb.syntax)
  • AW: returning hashes, and arrays
    ... It is much better to use reference when passing or retrieving more than ... Retrieve the values from a sub as refereces. ... I'm having trouble returning a hash from a subroutine, ... Must the hash and array really be a reference ...
    (perl.beginners)
  • newbie baffled by de/referencing with subroutines
    ... and I want to use data from that array after the sub is finished. ... What's wrong with my reference and/or dereference, and how do I fix it? ...
    (comp.lang.perl.misc)