title: Appending values to Hash if key is same in Perl
body: <p></p>
  
  <p>Problem is to read a file with value at every new line. Content of file looks like</p>
  
  <pre class="lang-none prettyprint-override"><code>3ssdwyeim3,3ssdwyeic9,2017-03-16,09:10:35.372,0.476,EndInbound
  3ssdwyeim3,3ssdwyfyyn,2017-03-16,09:10:35.369,0.421,EndOutbound
  3ssdwyfxc0,3ssdwyfxfi,2017-03-16,09:10:35.456,0.509,EndInbound
  3ssdwyfxc0,3ssdwyhg0v,2017-03-16,09:10:35.453,0.436,EndOutbound
  </code></pre>
  
  <p>With the string before first comma being the Key and string in between last and second last comma the Value</p>
  
  <p>i.e. for the first line 3ssdwyeim3 becomes the key and 0.476 Value.</p>
  
  <p>Now as we are looping over each line if the key exists we have to concatenate the values separated by comma.</p>
  
  <p>Hence for the next new line as key already exists key remains <code>3ssdwyeim3</code> but the value is updated to <code>0.476,0.421.</code></p>
  
  <p>Finally we have to print the keys and values in a file.</p>
  
  <p>I have written a code to achieve the same, which is as follows.</p>
  
  <pre class="lang-perl prettyprint-override"><code>sub findbreakdown {
      my ( $out ) = @_;
  
      my %timeLogger;
  
      open READ, "out.txt" or die "Cannot open out.txt for read :$!";
  
      open OUTBD, "&gt;$out\_breakdown.csv" or die "Cannot open $out\_breakdown.csv for write :$!";
  
      while ( &lt;READ&gt; ) {
  
          if ( /(.*),.*,.*,.*,(.*),.*/ ) {
  
              $btxnId = $1;
              $time   = $2;
  
              if ( !$timeLogger{$btxnId} ) {
                  $timeLogger{$btxnId} = $time;
              }
              else {
                  $previousValue       = $timeLogger{$btxnId};
                  $newValue            = join ",", $previousValue, $time;
                  $timeLogger{$btxnId} = $newValue;
              }
          }
  
          foreach ( sort keys %timeLogger ) {
              print OUTBD "$_ ,$timeLogger{$_}\n";
          }
      }
  
      close OUTBD;
      close READ;
  }
  </code></pre>
  
  <p>However Something is going wrong and its printing like this</p>
  
  <pre class="lang-none prettyprint-override"><code>3ssdwyeim3,0.476
  3ssdwyeim3,0.476,0.421
  3ssdwyeim3,0.476,0.421
  3ssdwyfxc0,0.509
  3ssdwyeim3,0.476,0.421
  3ssdwyfxc0,0.509,0.436
  3ssdwyeim3,0.476,0.421
  3ssdwyfxc0,0.509,0.436
  </code></pre>
  
  <p>Whereas expected is:</p>
  
  <pre class="lang-none prettyprint-override"><code>3ssdwyeim3,0.476,0.421
  3ssdwyfxc0,0.509,0.436
  </code></pre>