Home > Archive > PERL Beginners > April 2007 > Passing Hashes to a Sub
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Passing Hashes to a Sub
|
|
| Yitzle 2007-04-26, 6:58 pm |
| Something's not working... and I'm not sure where.
I'm modifying working code and trying to make the hash non-global.
If %dHash is global, it all works perfectly well.
But when I try to pass it around... the writeHashToFile makes a 0 byte file.
I would appreciate if you could check if I'm passing the hash correctly.
When I pass a reference to a hash and modify the hash, I don't need to
return the has, do I?
sub run($$$) {
my ($from,$to,$fileName) = @_;
my %dHash;
...
parseHtmlData ( \%dHash, split(/\n/, get($url)) );
...
writeHashToFile($fileName, \%dHash);
}
sub parseHtmlData($@) {
my $hRef = shift; my %dHash = %$hRef;
foreach (@_) { # Read data
... # Sets the dHash values
}
}
sub writeHashToFile($$) {
my $fileName = shift;
my $hRef = shift; my %dHash = %$hRef;
... # Writes hash to file; used to. Now writes nothing at all...
}
Thanks!
| |
| Tom Phoenix 2007-04-26, 6:58 pm |
| On 4/26/07, yitzle <yitzle@users.sourceforge.net> wrote:
> sub parseHtmlData($@) {
> my $hRef = shift; my %dHash = %$hRef;
You've just made %dHash a copy of the data in the hash referred to by
$hRef. You can do all you want with the copy, but it won't change the
original hash.
One solution would be to add a line like this at the end of your sub:
%$hRef = %dHash; # copy the data back to the real hash
But that's not the best solution, for a number of reasons. (For one
thing, if you return early from the subroutine, you'll need to add
another line like that.) Instead, I'd fix your sub to work with the
reference, using $hRef wherever you used dHash.
Good luck with it!
--Tom Phoenix
Stonehenge Perl Training
|
|
|
|
|