Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove part of string in Perl

Tags:

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 ?

like image 794
user238021 Avatar asked Dec 02 '22 01:12

user238021


2 Answers

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.

like image 131
Wooble Avatar answered Dec 18 '22 13:12

Wooble


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...

like image 28
sergio Avatar answered Dec 18 '22 12:12

sergio