1

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!

1
  • I wonder if I'm using the push function incorrectly. Hmmm... Commented Nov 3, 2011 at 20:59

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Darkwater23, because campaign is not an array, it's a scalar. You need to dereference the scalar into an array via $campaign->[0] or @{$campaign}[0].
@Darkwater23, take a look at perldoc.perl.org/perlreftut.html for more on references.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.