Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Adding Hash Keys/Values

by Anonymous Monk
on Nov 08, 2012 at 15:47 UTC ( #1002932=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I am in need of a fix for the following. I need to append to the hash as shown. How is this done?

#!usr/bin/perl use strict; use warnings; my %table_hash = ( '0,0' => 'X', '0,1' => 'Y', '0,2' => 'Z', ); print join ",",%table_hash,"\n"; my $n=0; my $m=0; foreach $n (0..3) { $table_hash{'$n,0'} = $m; $m++; }; print join ",",%table_hash,"\n";

Comment on Adding Hash Keys/Values
Download Code
Replies are listed 'Oldest First'.
Re: Adding Hash Keys/Values
by Kenosis (Priest) on Nov 08, 2012 at 15:56 UTC

    Use double-quotes so $n is interpolated:

    $table_hash{"$n,0"} = $m;
Re: Adding Hash Keys/Values
by kennethk (Abbot) on Nov 08, 2012 at 15:57 UTC
    The answer to your immediate issue is that you need to use double quotes instead of single quotes if you want a variable value to interpolate into a string. Your line should therefore read $table_hash{"$n,0"} = $m;. See Quote and Quote like Operators in perlop.

    You are using compound keys to emulate a multidimensional array in your code, which is very Perl 4. With the addition of array references (a couple decades ago), I would do this with something like:

    #!usr/bin/perl use strict; use warnings; use Data::Dumper; my @table = ( ['X', 'Y', 'Z'], ); print Dumper \@table; my $m=0; foreach my $n (0..3) { $table[$n][0] = $m++; }; print Dumper \@table;

    See perlreftut.


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1002932]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (15)
As of 2015-07-07 16:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (91 votes), past polls