0

I am trying to change key with another name . Tried below code but getting some error:

my @array = qw(1 hello ue hello 3 hellome 4 hellothere);
my %hash = @array;

foreach (Keys %hash) { 
   s/ue/u/g;
}

Output Error: Illegal modulus zero at test.pl line 35.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170

1 Answers1

7

Perl is case-sensitive. You are looking for keys (lowercase):

my @array = qw(1 hello ue hello 3 hellome 4 hellothere);
my %hash = @array;

foreach (keys %hash) {  # <-- 
   s/ue/u/g;
}

You should really use strict; use warnings; at the top of all of your Perl modules/scripts. It will give you much better error messaging.

More to the point of your question, you can't update hash keys like that. You have to create a new key in the hash with the desired name, and delete the old key. You can do this nicely in a single line since delete returns the value of the hash key that was deleted.

use strict;
use warnings; 

my @array = qw(1 hello ue hello 3 hellome 4 hellothere);
my %hash = @array;

foreach my $key (keys %hash) {  # <-- 
   if ($key eq 'ue') {
      $hash{u} = delete $hash{$key};
   }
}

To tighten up the code even more, it's not actually necessary to iterate through the keys to determine if a specific key exists. The following single line could replace the for loop:

$hash{u} = delete $hash{ue} if exists $hash{ue};
Community
  • 1
  • 1
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170