tags:

views:

63

answers:

3

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[^>]+>"),
            );  
+6  A: 

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.

FM
Just a quibble (clarification): the hash values *are* scalar--and will be scalar in every possible hash constructor. If you want a key to refer to a *structure*, you have to specify that structure. If you pass a list instead of an arrayref, Perl will happily split that list into alternating keys and values. The problem is that it constructs a hash you don't want. `"Sno." => 5, '0' => 'ID', '20' => 1, ...`
Axeman
@Axeman Right -- well put.
FM
+6  A: 

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.

jkramer
A: 

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];
Paul Tomblin