开发者

remove part of string in Perl

开发者 https://www.devze.com 2023-03-23 10:11 出处:网络
my $input1 = \"hours\"; my $input2 = \"Total hours\"; my ($matching_key) = grep { /$input2/ } $input1; print \"Matching key :: $matching_key\";
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 ?开发者_如何学Go


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.


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


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;


Like so

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号