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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

return all arrays created by function

Status
Not open for further replies.

nawlej

Programmer
Mar 26, 2004
380
US
What is the easiest way to return all of the arrays created by a function when the names are not staticly defined by the function?
 
in your function, push a reference to each dynamically created array INTO another array. This being solution to your question, I have to imagine that the problem you are solving might be better served from some refactoring.

Code:
sub make_lists {
  my @all_dem_arrays;
  
  #bullshit creation of dynamically named arrays
  for(@_){
    my @{$_} = qw/1 2 3/; # this is your non-statically named array
    push @all_dem_arrays, \@{$_};  # this is you pushing a reference to it
  }

  return @all_dem_arrays;  # this is you returning a list of those reference
}

my @lists = make_lists('blondes', 'brunettes', 'redheads');

# and here you are proving that it worked
foreach my $list ( @lists ){
  print join(', ' => @{$list}), "\n";
}

But I digress - becuase this solution basically sucks. You would probably be better off NOT dynamicallly naming arrays, and just using a hash-of-arrays instead.

--jim
 
Not quite sure what you mean by this. Perhaps a short piece of code to give us a clue as to the type of array and naming you are using.

Although if you are saying you are creating lots of names on the fly, you could store the names and contents within a hash and return them something like:
Code:
{
  my %names;
  $names{$array1name} = \@array1;
  $names{$array2name} = \@array2;
  return map {@{$names{$_}}} keys %names; 
                       # returns all array values as single list
  return values %names # returns refs to each array
}

Although I suspect you're trying to do something slightly different to that.

Barbie
Leader of Birmingham Perl Mongers
 
Yeah I ended up doing it as a hash.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top