开发者

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

开发者 https://www.devze.com 2023-01-12 23:54 出处:网络
I am getting the warning with use of following syntax - my %data_variables = (\"Sno.\" => (5,0), \"ID\" => (20,1),

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), 
                "C开发者_高级运维ertificate" => (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[^>]+>"),
            );  


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.


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.


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消