I have the following routine:

sub remap { my %remap = qw{ THIS THAT BLACK WHITE TALL SHORT }; $remap{ $_[0] }; }

Put in TALL, get out SHORT... The use of a lexical sort of strikes me as being a little unnecessary, what I would like to do would be to just build an anonymous hash out of the qw list, and dereference it:

sub remap_anon { @{[qw{ THIS THAT BLACK WHITE TALL SHORT }]}->{$_[0]}; }

Cool! That actually compiles. I was tickled pink. Trouble is, I don't know what it does. It certainly doesn't do what I want it to. If I try to run it I get: Can't coerce array into hash at remapper line 15

So I googled around a bit, and the only solutions I see are what I had in the first place: dump the list into a hash and then dereference it. Drat. I tried enclosing the anonymous @{[...]} in an outer %{...] or even %{[...]}, but perl continues to choke with the same message. At this stage it's just shotgun debugging, and besides, the syntax is a net loss.

So my question is, even if perl can't do it by itself (because "You used an array where a hash was expected, but the array has no information on how to map from keys to array indices. You can do that only with arrays that have a hash reference at index 0"), is there a way to coerce perl to coerce an array into a list? And what does that message really mean?


print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'

In reply to Coercing an array into a hash by grinder

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.