2

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";
}
1
  • 2
    Shouldn't hardcode that "6". for (my $he= 0; $he<= 6; $he++) should be for (my $he=0; $he<@selections; $he++), and it would be more readable as for my $he (0..$#selections) Commented Oct 23, 2012 at 19:44

1 Answer 1

5

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};
}
Sign up to request clarification or add additional context in comments.

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.