> how do I return multiple arrays, hashes, etc from a subroutine?

You can't... but you can return references.

my ($x, $y) = foo(); # returns 2 references
my @x = @{$x}; # "dereference" back to an array
my @y = %{$y}; # "dereference" back to a hash

sub foo {
  my @x = (1,2,3);
  my %y = (k1 => 1, k2 => 2);
  return ([EMAIL PROTECTED], \%y);
}


...You can dereference the variables when you get them back, or you can use
the references directly.

my ($x, $y) = foo(); # returns 2 references

$x->[1]; # index #1 of the array
$y->{k1}; # the key "k1" of that hash

For more info check out the perldocs for perlreftut.

Rob


-----Original Message-----
From: Lance Murray [mailto:[EMAIL PROTECTED]
Sent: Tuesday, February 25, 2003 5:05 PM
To: [EMAIL PROTECTED]
Subject: How do I return multiple discrete arrays and/or hashes from a
subroutine?


Hello:
 
I know I can return multiple scalar values from a subroutine using an array,
but how do I return multiple arrays, hashes, etc from a subroutine?  For
example, the following snippet...
 
     my @ip_addresses = &getIPAddresses;
     my (@hostfile, @no_dname) = &getHostNames(@ip_addresses);
     print "\nHOSTFILE: ", scalar @hostfile,"\n",@hostfile;
     print "\nNO_DNAME: ", scalar @no_dname,"\n",@no_dname;
 
Generates this for output...
 
     HOSTFILE: 411
     NO_DNAME: 0
 
When what I REALLY want returned is this: (valid data)

 
     HOSTFILE: 44
     NO_DNAME: 367
 
The subroutine I'm using looks like this:
 
sub getHostNames {
  my (@hostfile,@no_dname,$bitbucket,$hostname);
  foreach my $ip_address (@ip_addresses) {
    my @results = `/usr/sbin/nslookup $ip_address 2>&1`;
    chomp @results;
    foreach (@results) {
      # [PARSE OUTPUT HERE]
    }
  }
  @hostfile, @no_dname;
}

 
Obviously the subroutine assignments are just merging the contents of the
last
subroutine evaluation statement (@hostfile, @no_dname), and is returning the
merged values to the first variable (@hostfile/411 elements).  How can I
return
discrete arrays and hashes from a subroutine?
 
Grateful for any help!
 
Lance
 
 

----------------------------------------------------------------------------
--
This message may contain confidential information, and is intended only for
the use of the individual(s) to whom it is addressed.


============================================================================
==

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to