The code below demonstrates that $x (scalar), @x (list), %x (hash) are different things.
Your instinct that anything with Perl using array indices is probably wrong, is correct.
#!/usr/bin/perl -w use strict; use Data::Dumper; my $tokens = "32,15,4,72,13,28,14"; my @tokens = (split/,/,$tokens); my %tokens = map {$_ => 1}@tokens; print Dumper (\%tokens); __END__ Prints: $VAR1 = { '4' => 1, '32' => 1, '28' => 1, '72' => 1, '13' => 1, '14' => 1, '15' => 1 };
Reconsidering your requirements, and I will say that this is bizarre:
#!/usr/bin/perl -w use strict; use Data::Dumper; my $tokens = "32,15,4,72,13,28,14"; my @tokens = (split/,/,$tokens); my $i=0; my %tokens = map {$_ => $i++}@tokens; print Dumper (\%tokens); __END__ Prints: VAR1 = { '4' => 2, '32' => 0, '28' => 5, '72' => 3, '13' => 4, '14' => 6, '15' => 1 };
Now again of course since this initialization, why would you need the scalar string at all?
my @tokens = qw (32 15 4 72 13 28 14); my $i=0; my %tokens = map {$_ => $i++}@tokens;
yields the same result as above.

Ok, I am going to go "crazy" here and ask why you want a hash in the first place? I am at a loss the see the usefulness of a hash here. Why do you think that you need it?


In reply to Re: Convert a string into a hash by Marshall
in thread Convert a string into a hash by vitoco

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.