Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning - "Odd number of elements in hash assignment" in perl

Tags:

perl

I am getting the warning with use of following syntax -

my %data_variables = ("Sno." => (5,0),
                "ID" => (20,1), 
                "DBA" => (50,2), 
                "Address" => (80,3), 
                "Certificate" => (170,4),
            );

But I dont get a similar warning at use of similar syntax.

my %patterns = ("ID" => ("(A[0-9]{6}?)"),
                "Address" => (">([^<]*<br[^>]+>[^<]*)<br[^>]+>Phone"),
                "Phone" => ("Phone: ([^<]*)<"),
                "Certificate" => ("(Certificate [^\r\n]*)"),
                "DBA" => ("<br[^>]+>DBA: ([^<]*)<br[^>]+>"),
            );  
like image 349
Shubham Avatar asked Aug 26 '10 11:08

Shubham


3 Answers

You need to change your parentheses to square brackets:

my %data_variables = (
    "Sno."        => [5,0],
    "ID"          => [20,1], 
    "DBA"         => [50,2], 
    "Address"     => [80,3], 
    "Certificate" => [170,4],
);

Hash values must be scalar values, so your lists of numbers need to be stored as array references (hence the square brackets).

In your second example, the parentheses are superfluous and just confuse the matter. Each set of parentheses contains just one scalar value (a string), each of which becomes a hash value.

like image 169
FMc Avatar answered Nov 07 '22 02:11

FMc


The difference is that "..." is a string (single scalar) and (5, 0) is a list of two scalars. So in the first snippet, you're actually doing this:

my %data_variables = ("Sno.", 5, 0, "ID", 20, 1, "Address", 80, 3, "Certificate", 170, 4);

Since hashes are just lists with an even number of elements, this will work when the number of elements is even, but will fail if it's odd like in your example.

If you want to store arrays as values in the hash, use [5, 0] instead.

like image 12
jkramer Avatar answered Nov 07 '22 01:11

jkramer


You're trying to put a list in as hash elements, and it sees them as more key/value pairs. What you really want to do is put array refs, like

my %data_variables = ("Sno." => [5,0],
                "ID" => [20,1], 
                "DBA" => [50,2], 
                "Address" => [80,3], 
                "Certificate" => [170,4],
            );

You can refer to the array elements as

   my $foo = $data_variables{"Sno"}->[0];
   my $bar = $data_variables{"Address"}->[1];
like image 3
Paul Tomblin Avatar answered Nov 07 '22 03:11

Paul Tomblin