Doug Dawson
Doug Dawson

Reputation: 1273

Can't get values when looping over an array of arrays

I created an array like so:

while(@results = $execute->fetchrow())
{
  my $active = 'true';

  if($results[1] == 0)
  {
    $active = 'false';
  }

  my @campaign = ($results[0], $active);
  push(@campaign_names, @campaign);
}

Later, when I need to access the name of the campaign (which is the first element of the campaign array), I can't seem to extract it. What is the proper syntax?

foreach $campaign (@campaign_names)
{
  print ????;
}

Thanks!

Upvotes: 1

Views: 81

Answers (2)

friedo
friedo

Reputation: 66968

The problem is you're pushing an array onto the end of @campaign_names, when what you want is an array reference. Here's how I'd write it:

while(@results = $execute->fetchrow())
{
  my $active = $results[1] ? 'true' : 'false';
  push @campaign_names, [ $results[0], $active ];
}

# later

foreach my $campaign( @campaign_names ) 
{ 
    my $name = $campaign->[0]; 
    my $active = $campaign->[1];
}

I've cleaned it up a bit by using a ternary conditional (?:) to figure out the value of $active. The [ ... ] constructs an anonymous array reference (a scalar pointing to an array) which is then pushed onto @campaign_names.

When we loop over those later, two important things to notice are that we use my in the loop variable to keep it local to the loop block, and that we use -> to dereference the elements in the array pointed to by the array reference.

Upvotes: 2

Oesor
Oesor

Reputation: 6642

That's not creating an array of arrays. my @campaign = ($results[0], $active); push(@campaign_names, @campaign); flattens and pushes $results[0] and $active into the @campaign_names array. Instead, push an arrayref:

  my @campaign = ($results[0], $active);
  push(@campaign_names, \@campaign);

or

  my $campaign = [$results[0], $active];
  push(@campaign_names, $campaign);

Arrays can only hold scalar values.

You'll want to refer to perldsc as you learn (perldoc perldsc, http://perldoc.perl.org/perldsc.html)

Upvotes: 1

Related Questions