in reply to Convert a string into a hash

I suspect all you want is-

my @code = split /,/, $tokens;

If you're keeping hash with indices as values, it makes more sense to use an array. There's also this if you really don't care about the indices-

my %code = map { $_ => 1 } split /,/, $tokens;

Update: there's also this but I think your original version is easier for most to read-

my %code; my @code = split /,/, $tokens; $code{$code[$_]} = $_ for 0 .. $#code;

Replies are listed 'Best First'.
Re^2: Convert a string into a hash
by vitoco (Hermit) on Aug 14, 2009 at 22:41 UTC

    I do need the corresponding values, because I'll sort a given list of tokens from this set. johngg got the idea!

    This was the best I could do:

    my %code = ( my $i = 0 or map { $_ => $i++ } split /,/, $tokens );

    but I wanted to have no temporary variables... ;-)

      Conditional my isn't allowed. Besides, your code doesn't compile. You want
      my %code = do { my $i = 0; map { $_ => $i++ } split /,/, $tokens };

      If you really want no explicitely declared temp variables, you can use the following:

      my %code = sub { map { $_[$_] => $_ } 0..$#_ }->( split /,/, $tokens ) +;

      But honestly, there's no need to limit the scope that badly. Either of the following are quite suitable:

      my $i = 0; my %code = map { $_ => $i++ } split /,/, $tokens;
      my @code = split /,/, $tokens; my %code = map { $code[$_] => $_ } 0..$#code;

        Conditional my isn't allowed. Besides, your code doesn't compile.

        Yes, it does... without use strict; !!!

        Thanks for point that out.

      I can see how you can do that but not why you'd want to do it. The array is sorted already. There is no information in a hash with index values that isn't in an array. So, unless I'm missing something, it buys you nothing except a speed penalty and obfuscates a simple operation/need. If you could explain what you're going to do with it in the end, you might get some more interesting answers approaches. :)

        There is no information in a hash with index values that isn't in an array.

        Yes and no. If you want to know "the position of a given number", the information is there in the array, but finding it is hard (O(N)). It's O(1) with a hash.

        my ($index) = grep $code[$_] == $x, 0..$#code; -vs- my $index = $code{$x};

        I'm sorry for not being so clear. English is not my native language, so I decided just to write the code in the usual way with a minimum of info about the context. I thought this thread as a perl coding hackers topic.

        BTW, my best code really was:

        my %code = (my $i = 0 or map {($_, $i++)} split(/,/, $tokens));

        The previous was an updated one using => instead of the subarray, a more elegant code based on your reply, but I didn't notice my mistake when I pasted the line.