Dear Monks,
I am running into this weird problem with variable scoping.
Below is my sub-routine, populatemessagedefs. I am passing hash reference and a string to the sub-routine.
Scope of the sub-routine is to populate hash by splitting the string ($Everythingelse) by ',' and inserting it in the hash.
Example <\br> $Everythingelse holds (Tom,18,Jack,22,Tim,30)
The sub-routine iterates in the foreach loop and inserts following in hash
Result Set:
Key->Tom Value->18
Key->Jack Value->22
Key->Tim Value->30
The problem is after every ‘foreach’ iteration '$i' resets to 0, even if I increment value of $i.
Am I missing something completely obvious?
sub populatemessagedefs() { my ($ref_to_msg_defs,$Everythingelse) = @_; my $temp_value; my $temp_key; my @Interface_Message_List = split (',',$Everythingelse); my $i=0; foreach my $field(@Interface_Message_List) { #In next iteration $i is ‘0’ again if ($i == 0) { $temp_key = $field; $i++; #Value of $i is 1 now } elsif ($i == 1) { $temp_value = $field; if (exists $ref_to_msg_defs->{$temp_key}) { if ($field > $ref_to_msg_defs->{$temp_key}) { $ref_to_msg_defs{$temp_key} = $field; $i--; } } else { $ref_to_msg_defs{$temp_key} = $field; $i--; } } } }

In reply to problem with variable scoping by parth00

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.