in reply to better way to convert a string into an array and an hash

I don't know if it's better, but you can do this:

my $string = "1:1,2:1,3:2,500:2,505:1"; my %hash = split /[:,]/, $string; my @array = keys %hash;

Whether it's better depends on how much you know and can guarantee about your data. :-)

Replies are listed 'Best First'.
Re^2: better way to convert a string into an array and an hash
by dragonchild (Archbishop) on Oct 05, 2004 at 15:08 UTC
    FYI: that's not functionally equivalent. You lose the ordering in @array.

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

      Indeed.

      There are a number of ways to preserve the order. Here's a slightly whimsical one:

      my $string = "1:1,2:1,3:2,500:2,505:1"; my %hash = split /[:,]/, $string; my @array = split /:.+?,?/, $string; # :-)
      or another:
      my $string = "1:1,2:1,3:2,500:2,505:1"; my %hash = my @array = split /[:,]/, $string; @array = @array[grep $_%2==0, 0..$#array];
      But these probably drive the original split idea far far into the ground :-)