basm101 has asked for the wisdom of the Perl Monks concerning the following question:

Hi
I am trying to assign single key-value pairs to a hash and something is going very wrong...I get the error messages Useless use of hash element in void context and Useless use of a variable in void context.
open(INFILE,$infile) or die "Can't open $infile\n"; print "opened $infile\n";<STDIN>; while(<INFILE>){ if(/(\s+)(\d+)(\.)(\s+)([A-Z]{2})(\s+)([A-Z]{5})/){ # this matches certain lines in my data files $number++; print "$2=>$5\n"; # this works and prints my key and value tha +t I want $hash_codes{$2}=>$5;#useless } }
Is the problem that I can't use $2 and $5 from my pattern match in this way ? I tried assigning like this:
$key = $2; $value = $5; $hash{$key}=>$value;
but no joy either. Please help !

Thanks
basm101

Replies are listed 'Best First'.
Re: Useless use of hash element in void context
by tachyon (Chancellor) on Sep 25, 2003 at 10:32 UTC

    The => operator aka the FAT COMMA is a synonym for a comma so Perl sees your code as:

    $hash_codes{$2},$5 # thus the useless use of hash element in void context. # there is also a useless use of scalar in void context as well. # you want $hash_codes{$2} = $5 # this is normal usage of => %hash = ( key1 => 'val1', key2 => 'val2' ); # which parses the same as: %hash = ( 'key1', 'val1', 'key2', 'val2' );

    The => is SYNTACTIC SUGAR to make hash assignments look spiffy.....It also lets you pass strinct and not bother to quote the LHS as shown

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: Useless use of hash element in void context
by broquaint (Abbot) on Sep 25, 2003 at 10:32 UTC
    The problem is that you're trying to use the 'fat comma' (=>) to assign to the hash, where in actual fact you just want the plain assignment operator e.g
    $hash_codes{$2} = $5;
    The 'fat comma' behaves just like the normal comma operator but stringifies its left-hand argument and if its left-hand argument is a bareword it is exempt from strict. See. the perlop manpage for more information on the assignment and 'fat comma' operators.
    HTH

    _________
    broquaint