Bob John
Bob John

Reputation: 3878

Trying to read elements in an array using a for loop

I'm trying to read elements from an array using a for loop, but I can't seem to get it working right. When I run the program, it prints out a weird "HASH", or doesn't print out anything. Can anyone help?

#!/usr/bin/perl
use strict;

my $he;
my @selections = {"Hamburger","Frankfurter","French Fries","Large Coke","Medium Coke","Small Coke","Onion Rings"};
my @prices = {3.49, 2.19, 1.69, 1.79, 1.59, 1.39, 1.19};

for($he= 0; $he<= 6; $he++)
{
      print "@selections[$he]";
      print "@prices[$he]\n";
}

Upvotes: 2

Views: 783

Answers (1)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185025

When you put {}, you explicitly ask perl to make a reference to a HASH. What you seems to need instead is using parenthesis to declare an ARRAY.

So :

#!/usr/bin/perl
use strict; use warnings;

my @selections = (
    "Hamburger",
    "Frankfurter",
    "French Fries",
    "Large Coke",
    "Medium Coke",
    "Small Coke",
    "Onion Rings"
);
my @prices = (3.49, 2.19, 1.69, 1.79, 1.59, 1.39, 1.19);

for(my $he = 0; $he <= 6; $he++)
{
    print "$selections[$he]=$prices[$he]\n";
}

Moreover, making arrays is more fun and less boring like that :

my @selections = qw/foo bar base/;

but it only works when you don't have any space for values.

NOTES

  • I recommend you to use use warnings; all the times
  • don't write @selections[$he] but $selections[$he]
  • no need to predeclare $he in the whole scope, see where I declare it
  • a better approach (depends of your needs) is to use a HASH instead of two ARRAYS :

like this :

#!/usr/bin/perl -l
use strict; use warnings;

my %hash = (
    "Hamburger" => 3.49,
    "Frankfurter" => 2.19,
    "French Fries" => 1.69,
    "Large Coke" => 1.79,
    "Medium Coke" => 1.59,
    "Small Coke" => 1.39,
    "Onion Rings" => 1.19
);

foreach my $key (keys %hash) {
    print $key . "=" . $hash{$key};
}

Upvotes: 5

Related Questions