1

I am a newbie in newbies for perl. I am trying to create a function which returns the value of the hash. The following piece of code simply returns the last index of the hash. I googled around and couldnt find what i need. Appreciate if anyone can tell me where I am going wrong.

I am expecting, if I pass "he_1", I should get a return back value of 1, etc.. but all I see is 9.

#!/usr/bin/perl

my %IndexMap = ();

my $MAX_V = 5;
my $MAX_T = 10;

sub InitIndexMap {
   foreach my $i (0..$MAX_V-1) {
      $IndexMap["he_".$i] = $i;
      print "he_".$i;
      print $IndexMap["he_".$i];
   }

    foreach my $i ($MAX_V..$MAX_T-1) {
      $IndexMap["un".$i] = $i;
      print "un".$i;
      print $IndexMap["un".$i];
    }
}

sub GetVal {
   my ($name) = @_;
   return $IndexMap[$name];
}

&InitIndexMap();
my ($index) = &Getval("he_4");
print $index;
mob
  • 117,087
  • 18
  • 149
  • 283

2 Answers2

7

To read a hash, use curly braces, not brackets. Try this:

sub InitIndexMap {
    foreach my $i (0..$MAX_V-1) {
        $IndexMap{ "he_" . $i } = $i;
        print "he_".$i;
        print $IndexMap{ "he_" . $i };
    }

    foreach my $i ($MAX_V..$MAX_T-1) {
        $IndexMap{ "un" . $i } = $i;
        print "un".$i;
        print $IndexMap{ "un" . $i };
    }
}

sub GetVal {
    my ( $name ) = @_;
    return $IndexMap{ $name };
}

You should add this to the top of the script:

use strict;
use warnings;

The general rule to always turn those pragmas. They warnings and errors that that cause would have probably led you to the answer to your question.

ikegami
  • 367,544
  • 15
  • 269
  • 518
gpojd
  • 22,558
  • 8
  • 42
  • 71
  • 2
    strict and warnings should be turned on at the top of the script in all cases, not just for people learning perl. – qqx Nov 30 '12 at 21:17
  • 1
    This better explains what I mean than I can: http://perl.plover.com/yak/12views/samples/notes.html#sl-31. I should also add that if you know what you are doing, sometimes you MUST turn off the strict pragma to do some really clever things. There's nothing wrong with that if you understand the consequences. – gpojd Nov 30 '12 at 21:19
  • 2
    Turning them off means you had them on to begin with, as you should. Fixed the post. – ikegami Nov 30 '12 at 21:24
  • @gpojd When you said "really clever things" I think what you really meant was "really stupid things that could easily have been solved with proper perl code". – TLP Nov 30 '12 at 21:28
  • most really clever things can be done even under strict by using even *more* clever code than the non-strict level of cleverness - but you really don't want to go there – ysth Nov 30 '12 at 22:08
3

You should access hashes with curly brackets like { and }.

$hash_name{$key} = $value;

In your example.

$IndexMap{"he_".$i} = $i;

You should consider doing some tutorials. This is VERY BASIC knowledge in Perl.

Boris Däppen
  • 1,186
  • 7
  • 20