Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hash problems in Perl

Status
Not open for further replies.

thegman

Programmer
Oct 16, 2001
26
GB
Is it possible in Perl to create a Hash structure and somehow 'flatten' it so that it may be delievered as an argument to a function without a making a reference to it? The reason I do not want to make a reference is because I want to ditch the real hash to use many times over, and this seems to invalidate the reference. What I need to do is to make a 'stand alone' hash which can be passed around functions without any kind of reliance on any other variable. Possible?

TIA

Garry
 
'sounds to me like references are the way to go. If you pass a reference to your hash to each routine, then you keep one hash and each routine can operate on it.

Can you sketch out the flow and effect you're trying to achieve? 'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
It's OK, I achieved what I wanted, rather than create the reference to the hash in the main subroutine, I passed the hash to a different subroutine, whose only purpose was to make a reference to the hash and pass it back, seems that this will make a unique reference every time, and seemingly make a copy of the hash.

Thanks anyway
 
Code:
#!perl
# it still sounds like you are jumping through a few to many
# hoops.  The following illustrates setting up a hash and 
# passing references to that hash into several trivial 
# sub routines.  Each sub modifies the hash.

use strict;

my %hash = ( color=>'blue');

red(\%hash);
print "RED: $hash{color}\n";

green(\%hash);
print "GREEN: $hash{color}\n";

blue(\%hash);
print "BLUE: $hash{color}\n";

#------------------------------------------------------
# SUBS
sub red  {
  my $hash_ref = shift;
  $$hash_ref{color} = 'red'; 
  }
sub green  {
  my $hash_ref = shift;
  $$hash_ref{color} = 'green';
  }
sub blue  {
  my $hash_ref = shift;
  $$hash_ref{color} = 'blue';
  }
'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top