开发者

perl substr to get a substring

#!/usr/bin/perl

my $str = "abc def yyy ghi";

print substr($s开发者_运维技巧tr, 0 , index($str,' '));

I want substr to print def yyy

print substr ($str, index ($str, ' '), rindex($str, ' ') does not work?

Any idea?


You didn't specify EXACTLY what you want as far as logic but the best guess is you want to print characters between first and last spaces.

Your example code would print too many characters as it prints # of characters before the last space (in your example, 10 instead of 7). To fix, you need to adjust the # of characters printed by subtracting the # of characters before the first space.

Also, you need to start one character to the right of your "index" value to avoid printing the first space - this "+1" and "-1" in the example below

$cat d:\scripts\test1.pl
my $str = "abc def yyy ghi";

my $first_space_index = index ($str, ' ');
my $substring = substr($str, $first_space_index + 1, 
                             rindex($str, ' ') - $first_space_index - 1);
print "|$substring|\n";


test1.pl
|def yyy|


The third argument is length, not offset. But it can be negative to indicate chars from the end of the string, which is easily gotten from rindex and length, like so:

my $str = "abc def yyy ghi";
print substr( $str, 1 + index( $str, ' ' ), rindex( $str, ' ' ) - length($str) );

(Note adding 1 to get the offset after the first space.)


If you want to print text between first and last space, wouldn't it be easier with regex?

print $1 if "abc def yyy ghi" =~ / (.*) /


frankly, substr/index/rindex are really not the way to go there. You are better off doing something like:

my $str = "abc def yyy ghi";
my @row = split ' ', $str;
pop @row and shift @row;
print "@row";

Which is more inefficient, but captures the actual intent better

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜