in reply to hash symbolic references
When $number is equal to 1 in keys %{ $input{$number} }, you end up with keys %{ $input{"1"} } which is keys %{"0"}, so you are trying to read the keys of a hash named 0. Under strict, perl won't let you use a string as a ref. Luckily %{"0"} is unlikely, so when you want the keys of that hash, perl finds none, and it does what you want unless strict is present. But with $number equal to 4, you will try to look into %string which may really well exist, and you'll be using the values of an existing hash by mistake... oups!
Before looking at the content of the hash, you must check that it actually is one: if (ref $input{$number} eq 'HASH').
So here strict did not tell you about something that did not go as you wanted, it warned you about a disaster ready to happen. And warnings helps a lot too.
Now you know how to correct that code. But do you actually need it? It look like you're trying to output JSON from perl data. If your input data structure is a hash and you want an array you'll have to make a conversion (@list = map $hash{$_}, sort keys %hash;), but you may get just what you want and need with a working module. Try that on the command line (if you're on windows, you may want to replace the ' by "):perl -MJSON -MData::Dumper -e '$data = [0, 1, 2, { a => 1, b => 2}, qq<String>]; print Dumper $data; print encode_json $data;'
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: hash symbolic references
by numele (Sexton) on Jan 29, 2015 at 00:26 UTC | |
by Mr. Muskrat (Canon) on Jan 29, 2015 at 18:35 UTC |