Search code examples
perlhashperl-data-structures

Perl push values in a hash


I am always confusing or don't know how to handle hash in perl.

So here is the problem,

Considering the whole thing, i am trying to change the key name in the below hash.

my %hash_new = {
  'customername' => 'Lee & toys',
  'employee_name' => 'Checngwang',
  'customer_id' => 'X82349K',
  'customer_address' => 'classic denver ranch, meadows drive',
  'types' => 'category la',
};

my %selectCols = ('customername' => 'CUSTOMERNAME','employee_name' => 'EMP_NAME','customer_id' => 'cusid','customer_address' => 'cusaddr','types' => 'Typs');

my %new_hash = ();

foreach my $hash_keys (keys %hash_new){
   my $newKey = $selectCols{$hash_keys};
   $new_hash{$newKey} = $hash_new{$hash_keys};
}

print Dumper %new_hash;

Output of %new_hash is something like a key value combination of continuous string as below,

CUTOMERNAMELee & toysEMP_NAMEChecngwangcus_idX82349Kcusaddrclassic denver ranch, meadows driveTypscategory la

But instead of this, i need the hash like,

$VAR1 = {
      'CUSTOMERNAME' => 'Lee & toys',
      'EMP_NAME' => 'Checngwang',
      'cusid' => 'X82349K',
      'cusaddr' => 'classic denver ranch, meadows drive',
      'Typs' => 'category la',
    };

Please help me around this!


Solution

  • If I understood you correctly, then this works:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use Data::Dumper;
    
    
    my %hash_new = (
      'customername' => 'Lee & toys',
      'employee_name' => 'Checngwang',
      'customer_id' => 'X82349K',
      'customer_address' => 'classic denver ranch, meadows drive',
      'types' => 'category la'
    );
    
    my %selectCols = (
      'customername' => 'CUSTOMERNAME',
      'employee_name' => 'EMP_NAME',
      'customer_id' => 'cusid',
      'customer_address' => 'cusaddr',
      'types' => 'Typs'
    );
    
    my %new_hash = ();
    
    foreach my $hash_keys (keys %hash_new){
       my $newKey = $selectCols{$hash_keys};
       $new_hash{$newKey} = $hash_new{$hash_keys};
    }
    
    print Dumper \%new_hash;
    

    The only code I changed in your code was using () instead of {} in %hash_new and escaped the % in the Dumper statement. The % should be escaped because Dumper expects a reference, not a hash (that's true also for all other Perl variable types in use with Dumper).

    Output:

    $VAR1 = {
          'Typs' => 'category la',
          'cusaddr' => 'classic denver ranch, meadows drive',
          'EMP_NAME' => 'Checngwang',
          'cusid' => 'X82349K',
          'CUSTOMERNAME' => 'Lee & toys'
        };
    

    Also, don't use confusing names like %hash_new and %new_hash. It's - well - confusing.