user238021
user238021

Reputation: 1221

remove part of string in Perl

my $input1 = "hours";
my $input2 = "Total hours";
my ($matching_key) = grep { /$input2/ } $input1;
print "Matching key :: $matching_key";

What I want is to strip "Total" from $input2 and assign it back to input2 so my grep line will match. how can I strip that word ?

Upvotes: 6

Views: 98701

Answers (4)

user842209
user842209

Reputation:

I'm not sure exactly what you're asking, but if you want $input2 to be 'Total', try

$input2 =~ s/ hours//;

or

$input2 = substr $input2, 0, 5;

Similarly, if you want $input2 to be 'hours', try

$input2 =~ s/Total //;

or

$input2 = substr $input2, 6;

Upvotes: 4

Wooble
Wooble

Reputation: 89867

If I'm understanding your question correctly, you want

$input2 =~ s/Total //;

However, you're also misusing grep(); it returns an array of elements in its second parameter (which should also be a list) which match the pattern given in the first parameter. While it will in fact return "hours" in scalar context they way you're using it, this is pretty much coincidental.

Upvotes: 11

Ray Toal
Ray Toal

Reputation: 88378

Like so

my $input1 = "hours"; 
my $input2 = "Total hours";
$input2 =~ m/($input1)/;
print "Matching key : $1\n";

Upvotes: 0

sergio
sergio

Reputation: 69027

I am not sure that I understand fully your question, anyway you can strip Total like this:

$input2 =~ s/Total //;

after this $input2 will have the value "hours".

I don't understand fully the "assign it back to input2 so my grep line will match" part...

Upvotes: 6

Related Questions