Perl for loop error

I am new to the Perl, I was trying to execute a simple program as encoded below using Strawberry perl 5, version 16:

#!usr/bin/perl

use warnings;
use strict;

my @array= {1,2,3,5,7,9};
my $i;

foreach $i (@array)
{
print qq(Element is $i\n);
}

I am getting the below as output:

Element is HASH(0x3f8b4c)

However the output that I should receive is:

Element is 1
Element is 2
Element is 3
Element is 5
Element is 7
Element is 9.

Appreciate your help in this.

Answers


To initialize an array, use a list like

my @array = (1, 2, 3, 5, 7, 9);

Note: The parens just sort out the precedence, they are not a special array syntax.

Curlies delimit an anonymous hashref, like

my $foobar = {
  foo => "bar",
  baz => "qux",
};

So what happened is that you assigned to your array a list of one anonymous hashref, just like

my @array = ({
  1 => 2,
  3 => 5,
  7 => 9,
})

would have worked.


you should use () to define an array instand of {},{} is used to defind a hash

#!usr/bin/perl

use warnings;
use strict;

my @array= (1,2,3,5,7,9);
my $i;

foreach $i (@array)
{
  print qq(Element is $i\n);
}

#!usr/bin/perl

use warnings;
use strict;

my @array= (1,2,3,5,7,9);

foreach my $i (@array)
{
print "Element is ", $i,"\n"; ##Or as u want..many ways to do things in perl
}

Try like this. The array should be in parenthesis. Curly braces to be used in hashes.


Need Your Help

Why is an iframe in XUL popup not displayed?

iframe firefox-addon xul

I'm trying to create addon for Firefox that will play on-line radio. I need to dispaly an iframe with radio player.

Reflectively save domain class instances in Grails

json grails reflection polymorphism

The problem is as follows: I want to handle a POST request with JSON body. The body consists of an array of JSON Objects, without further nesting, i.e. simple HashMaps. All of these objects represent

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.