in reply to Re: Another flatfile thingy
in thread Another flatfile thingy

@{$hash->{$columns[0]}}{@headers} = @columns;Now that has to be one of the coolest things I've seen here lately... Congrats, dude. You hit the nail on the head it seems. Thanks for your views.

#!/home/bbq/bin/perl
# Trust no1!

Replies are listed 'Best First'.
RE: (bbq) RE: Re: Another flatfile thingy
by btrott (Parson) on Aug 04, 2000 at 20:10 UTC
    You wrote:
    > Forgive me for my dense question, but how do you return > a reference of a hash if the hash is private to the > subroutine? Can that be done?
    Don't think of the hash as "private" to the subroutine; yes, it's declared lexically within the sub, but that's not all that matters. Think of the hash as a piece of data *somewhere* that you've referenced lexically within the sub.

    Perl's garbage collection is based on reference counting; so each reference to such a piece of data increments the reference count. Once you've declared

    my $hash = {}
    the reference count of the underlying structure is incremented to one.

    Normally, you'd just have that one reference to the data, so once the lexical has gone out of scope--at the end of the subroutine--the data would be destroyed. But not here, because you've returned a reference to the data and assigned it somewhere else. Even though leaving the sub decrements the reference count, then, you re-increment it by assigning the return value of the sub. So the reference count is still one, and the data is still there, and valid.

    The data won't be destroyed until all references to it have gone away.

    BTW: this is, as far as I know, correct, but someone who knows more about Perl's internals is free to correct anything wrong. :)