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;'


In reply to Re: hash symbolic references by Eily
in thread hash symbolic references by numele

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.