in reply to Simple hash assignment...or is it?

Various things...

First you're using local where I think you mean my. Second, you've got your hash assignment backwards. If you want

foreach (@tcp_utilization_metrics) { print "$tcp_utilization_adapter_names{$_}\n"; }
to actually print something, then you need to change
$tcp_utilization_adapter_names{"$if_name"} = "$network_if";
to
$tcp_utilization_adapter_names{$network_if} = $if_name;
Michael

Replies are listed 'Best First'.
Re: Re: Simple hash assignment...or is it?
by arootbeer (Novice) on Nov 22, 2003 at 01:08 UTC
    I'm keying my hash on $if_name, not $network_if, because $if_name should be equivalent to one member of @tcp_utilization_metrics, which I use to loop through each value in the hash. Please notice that $if_name is assigned the same value as $network_if at the top of the loop, but $network_if is the variable whose value is changed during the loop.
      Rats - read it backwards :-(

      Well - I just ran your code here (on linux), adding "use strict", and adding "my" as appropriate, and it ran correctly (or at least I don't have any empty lines anywhere).

      Ah - I know what the problem is:

      foreach $network_if (@tcp_utilization_metrics) { local $if_name = $network_if; if ($network_if =~ /en/) { $network_if =~ substr ($network_if, 2, 0, "t"); }
      When change the $network_if value here you actually modify the @tcp_utilization_metrics array - see the docs on the behavior of the foreach loop.

      If you reverse things you should be fine:

      foreach $if_name (@tcp_utilization_metrics) { local $network_if = $if_name; if ($network_if =~ /en/) { $network_if =~ substr ($network_if, 2, 0, "t"); }
      That said - you should "use strict" and replace those "local" with "my".

      Michael

        Wow...that's exactly the problem. I added a Dump after the second foreach loop, and came up with this:

        $VAR1 = {
                  'en0' => 'ent0',
                  'en1' => 'ent1' 
                };
        $VAR1 = (
                  'ent0',         
                  'ent1'          
                );

        Thanks so much! That's a heck of a caveat...err...feature to have.

        P.S. The following is the docs on the foreach loop that are in my Camel (Ver. 1):

        The foreachloop iterates over a list value and sets the control variable (var) to be each element of the list in turn...

        I guess that implicitly states what you said, but it's not extremely obvious...