in reply to Re: Convert a string into a hash
in thread Convert a string into a hash

Ok, I am going to go "crazy" here and ask why you want a hash in the first place?

I just want to iterate the elements of another list of tokens, but in the same order them appear in the main list of tokens. Simplified:

my $tokens = "32,15,4,72,13,28,14"; my %code = do { my $i = 0; map { $_ => $i++ } split /,/, $tokens }; my $list = "4,13,15"; my $ok; for my $token (sort { $code{$a} <=> $code{$b} } split /,/, $list) { print "$token "; # more code with $token... last if $ok; } __END__ 15 4 13

Obviously, both $tokens and $list are dynamically loaded from somewhere else...

Replies are listed 'Best First'.
Re^3: Convert a string into a hash
by Marshall (Canon) on Aug 15, 2009 at 07:05 UTC
    This is a straight-forward implementation.
    Post again if I didn't get it right....
    #!/usr/bin/perl -w use strict; my $tokens = "32,15,4,72,13,28,14"; my @tokens = split (/,/, $tokens); my $list = "4,13,15"; my @list = split (/,/,$list); my %list = map {$_ => 1}@list; my @ordered_nums = grep{$list{$_}}@tokens; print "@ordered_nums\n"; __END__ PRINTS: 15 4 13

      That was the other aproach I thought, but the requirement changed to pick only the best token from $list, which is loaded many times based on some external events, while %code is initialized once.

      Based on the previous, I decided to keep that part, and now I want to rewrite:

      my $best = 14; # actually, last value from $tokens. for my $b (split /,/, $list) { $best = $b if $code{$b} < $code{$best}; }

      Update: syntax error, extra ")"...

        but the requirement changed to pick only the best token from $list

        Can you define what "best" means?
        Give a text description and then several examples.

Re^3: Convert a string into a hash
by Marshall (Canon) on Aug 15, 2009 at 07:18 UTC
    Ooops, mess up and double post...sorry.... This is a straight-forward implementation.
    Post again if I didn't get it right....
    #!/usr/bin/perl -w use strict; my $tokens = "32,15,4,72,13,28,14"; my @tokens = split (/,/, $tokens); my $list = "4,13,15"; my @list = split (/,/,$list); my %list = map {$_ => 1}@list; my @ordered_nums = grep{$list{$_}}@tokens; print "@ordered_nums\n"; __END__ PRINTS: 15 4 13
    Update: I would perhaps replace "list" with "list_order". Matter of choice.