SPUG: hashes, arrays, map, join

Colin Meyer cmeyer at helvella.org
Fri Mar 9 19:38:17 CST 2001


On Fri, Mar 09, 2001 at 04:53:06PM -0800, John Cokos, CEO, iWeb, Inc. wrote:
> I've been knocking my head agains the wall all day 
> on this stupid little problem ... somebody please
> bail me out.
> 
> Assume a string like this.
>    my $results = "12345:15,32984732:25,733263:12,349874:5";
> 
> I want to place it into a hash, keyed by the first number,
> valued by the second one.  That's not a problem.
>    my %ids = ();
>    %ids = map { split(/\:/) } split(/\,/,$results);
> 
> Now, I need to add (or delete) some of these keys.
>    delete $ids{12345};
>    $ids{5555} = 12;
> 
> Again, no problem, that works.
> 
> The pickle, is getting this updated hash back into the comma
> separated format that it started with.  Totally lost here.
> 
> This just flattens it.
>          print join(",", %ids);
> 
> This works, but it's hideous (gotta be a smoother way).  I can
> see this being a pretty intense maneuver on a large set:
>           my %set = ();
>           my @array;
>           foreach my $key ( keys %ids) { push @array, "$key:$ids{$key}"; }
>           print join(",", @array);
> 

How about: 
$r = join ',', map "$_:$ids{$_}", keys %ids;

-C.

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/





More information about the spug-list mailing list