Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-19 21:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found