in reply to Appending values to existing hash key

A number of minor things, most of which are personal preference:

  1. I tend to use statement modifiers where there would only otherwise be one small statement in a controlled block.
  2. remove the trailing white space from the captured strings and require at least one of each character type in the regex to avoid some nasty edge cases
  3. Avoid intermediate variables where the calculation is trivial (@val for example)
  4. Use double quote interpolation instead of concatenation
  5. #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash; while (<DATA>) { (my $key, my $value) = /(\S+\s+\S+)\s+(\S+\s+\S+)/; $value = join ":", split " ", $value; $hash{$key} .= ", " if exists $hash{$key}; $hash{$key} .= $value; } print "$_ $hash{$_}\n" for sort keys %hash; __DATA__ id1 name1 cat1 catname1 id1 name1 cat2 catname2 id2 name2 cat3 catname3 id3 name3 cat1 catname1 id3 name3 cat4 catname4

    Prints:

    id1 name1 cat1:catname1, cat2:catname2 id2 name2 cat3:catname3 id3 name3 cat1:catname1, cat4:catname4
    If the code changes take longer than the time saved, it's fast enough already.

Replies are listed 'Best First'.
Re^2: Appending values to existing hash key
by jaypal (Beadle) on Mar 21, 2014 at 03:34 UTC

    Thank you so much for replying so fast and hitting all my pain points. This is exactly what I was looking for

    $value = join ":", split " ", $value; # This is awesome $hash{$key} .= ", " if exists $hash{$key}; # I was thinking more i +n lines of a ternary op but this is short and concise too $hash{$key} .= $value; } print "$_ $hash{$_}\n" for sort keys %hash; # I definitely like this a +pproach

    Thank you once again!