Why is Perl hash value added as a key?
perl
Solution
There is a relationship between arrays and hashes that you're hitting:
my %hash = ( one => 1, two => 2, three => 3 );
This creates a three member hash with the keys `one`, `two`, and `three. So does this:
my %hash = ( "one", 1, "two", 2, "three", 3 );
In fact, these two lines are exactly the same statement. The `=>` is a form of syntactic sugar used to highlight the relationship between one value and another. Here's the same line again. I'm just messing with your brain in this one, but it produces the same hash as before:
my %hash = ( "one", 1 => "two", 2 => "three", 3 );
Here's another way of assigning the same hash:
my @array = ( "one", 1, "two", 2, "three", 3 );
my %hash = @array;
And this is also valid too:
my @array = %hash;
There's a strong relationship between hashes and arrays in Perl. If you take an array in a hash context, it becomes a hash. If you take a hash in an array context, it becomes an array. For example:
mysub (%hash);
sub mysub {
my %subhash = @_;
...
}
This is a valid (although not recommended way) of passing a hash to a subroutine. The hash is translated into the `@_`array which then gets translated back to a hash in the subroutine.
Let's take a look at your loop:
for my $k1 (%read_data) {
The `(...)` is a list/array context, and thus will take your `%read_data` hash, and present it in a list context with each key followed by its value.
There are a few ways to fix this. One is to use the keys to pull out all of the keys in a hash and return an array of the keys. This is usually combined with sort to sort the keys into some semblance of order.
for my $k1 ( sort keys %read_data ) {
Another is to use the each which returns a series of two member arrays with one key and one value.
Problem
I have a hash `my %read_data = ();` I am trying to build up keys and values like this ``` $read_data{"status"} = 0; $read_data{"suffix"} = "_SP"; $read_data{"consumption"} = 95; ``` What I am seeing is as follows, and I cannot figure out what I am doing wrong. ``` Key=status Key=0 Key=suffix Key=_SP Key=consumption Key=95 ``` I am printing this using ``` for my $k1 (%read_data) { print "Key=".$k1."\n"; } ```