CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Array in Scalar Context

 



zak100
User

Feb 22, 2017, 6:09 AM

Post #1 of 4 (1568 views)
Array in Scalar Context Can't Post

Hi,
I am reading a book which says that:
an array evaluated in scalar context produces the number of elements in the array:
I have written a simple code:

#!/usr/bin/perl
use strict;
use warnings;
use v5.10;


my @items = {"first", "Second", "Third"};
my $count = @items;
say "elements in array are $count";



I am getting following error & wrong output

>perl elementsinArray.pl
Odd number of elements in anonymous hash at elementsinArray.pl line 7.
elements in array are 1


Can some body please guide me whats the problem in my understanding?

In my view it should print 3 because there are 3 elements in aray. I cant understand the error message.
Zulfi.


FishMonger
Veteran / Moderator

Feb 22, 2017, 6:20 AM

Post #2 of 4 (1565 views)
Re: [zak100] Array in Scalar Context [In reply to] Can't Post

The problem is with this line:

Code
my @items = {"first", "Second", "Third"};


The curly braces are used for hashes, not arrays. Change them to ( ) parens.

Code
my @items = ("first", "Second", "Third");



BillKSmith
Veteran

Feb 22, 2017, 7:51 AM

Post #3 of 4 (1561 views)
Re: [zak100] Array in Scalar Context [In reply to] Can't Post

FishMonger has already given you the correction you need. I will try to explain your output.

The message tells you that the problem is in the seventh line:

Code
my @items = {"first", "Second", "Third"};


The braces {...} create an anonymous (no name) hash and return a reference to it. The '=' stores that reference as the one and only element in the array. Because a hash stores key/value pairs, an even number of elements is required. You are trying to store an odd number (3) of strings in that hash. This is almost always an error, hence the warning message.

Your program correctly outputs the number (1) of elements in the array. As I said earlier, that element contains a reference to the hash which you (accidentally) created.
Good Luck,
Bill


zak100
User

Feb 22, 2017, 9:20 AM

Post #4 of 4 (1555 views)
Re: [BillKSmith] Array in Scalar Context [In reply to] Can't Post

Hi,
Thanks for the explanation & for solving the problem.

Zulfi.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives