Reputation: 7854
I'm trying to use the map
function in Perl to replace part of an array of strings with a letter C
, but I can't figure out the regex to do so. (I have to use map
, no option to not use it.) Perl is returning 1
for each part of the array rather than the correct string but with C
instead of the numbers.
Basically, I have the below array in Perl, and I need to change the numerical value to C
. I need to use map
to do so, and I'm not sure how to go about it. I tried @GradeC = map(s/7[2-9]/C/, @GradeC);
, as my Google-fu showed that that could be how to find/replace using regex, but that doesn't work. Full disclosure: this is homework, but I am allowed to use Stack Overflow for help.
@GradeC = ("Name: Shemp Grade: 79",
"Name: Curly Grade: 75",
"Name: Larry Grade: 72");
# map statement
print join("\n", @GradeC);
Upvotes: 1
Views: 160
Reputation: 126722
This "allowed to use any and all resources available" business is ridiculous.
This
use strict;
use warnings;
my @grade_c = (
'Name: Shemp Grade: 79',
'Name: Curly Grade: 75',
'Name: Larry Grade: 72',
);
print "$_\n" for map s/grade\s*:\s*\K\d+/C/r, @grade_c;
output
Name: Shemp Grade: C
Name: Curly Grade: C
Name: Larry Grade: C
And I am sure you have learned nothing.
Upvotes: 1
Reputation: 35198
If you want to be edit your existing structure, than just use a for.
for (@GradeC) {
s/7[2-9]/C/;
}
If you really want a new array, then don't forget to return your value after the substitution. Also, as ikegami pointed out, you don't want to perform on $_
directly as that will edit your original array, so instead use a temporarily var.
my @newGrades = map { my $g = $_; $g =~ s/7[2-9]/C/; $g } @GradeC;
Upvotes: 3
Reputation: 107040
use strict;
.use warnings;
use feature qw(say);
and you get to use the say
statement.Map takes the elements in the array, sets each one to $_
and then runs the command against it. It also aliases each instant of $_
with the actual value in the array, so you don't have to do anything.
I'm using s/7\d/C/
which replaces each instant of 7 followed by a digit with the letter C.
#! /usr/bin/env perl
#
use warnings;
use strict;
use feature qw(say);
my @grade_c = (
"Name: Shemp Grade: 79",
"Name: Curly Grade: 75",
"Name: Larry Grade: 72"
);
map { s/7\d/C/ } @grade_c;
say join "\n", @grade_c;
Runs:
Name: Shemp Grade: C
Name: Curly Grade: C
Name: Larry Grade: C
Upvotes: 3