I have a hash with indexes like "Bonus", "Plusbonus", "Plusbonus_001", "Plusbonus_001", ...
Now I'm looking for a possibility to handle these keys in a loop. (But, there are many others not to handle!)
I tried
use strict;
use warnings;
for ("Bonus", "Plusbonus", "Plusbonus_001" .. "Plusbonus_010") {
# do some stuff
}
But I get the error Argument "Plusbonus_001" isn't numeric in range (or flop) at ./test.pl line 14.
Without the _
/underscore it works well.
I used
use strict;
use warnings;
for ("", "001" .. "010") {
my $index = "Plusbonus" . ($_ ? "_$_" : "");
# do some stuff by using $index instead of $_ as key
}
But now, with "Bonus", there is another key to handle so that my workaround doesn't work anymore.
Is there a possibility to generate these keys on another short way?
CodePudding user response:
You can use map to build a range:
use warnings;
use strict;
for (map { sprintf 'Plusbonus_d', $_ } 0 .. 10) {
print "$_\n";
}
Prints:
Plusbonus_000
Plusbonus_001
Plusbonus_002
Plusbonus_003
Plusbonus_004
Plusbonus_005
Plusbonus_006
Plusbonus_007
Plusbonus_008
Plusbonus_009
Plusbonus_010
CodePudding user response:
In the spirit of using the magic string increment as attempted, you can use the following. It's short but not easy to read.
use strict;
use warnings;
for ("Bonus", "Plusbonus", map { "Plusbonus_" . $_ } "001" .. "010") {
# do something
}