kal
kal

Reputation: 29351

perl substr to get a substring

#!/usr/bin/perl

my $str = "abc def yyy ghi";

print substr($str, 0 , index($str,' '));

I want substr to print def yyy

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

Any idea?

Upvotes: 2

Views: 4121

Answers (4)

hlynur
hlynur

Reputation: 596

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" =~ / (.*) /

Upvotes: 2

ysth
ysth

Reputation: 98388

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

Upvotes: 3

ivancho
ivancho

Reputation: 899

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

Upvotes: 1

DVK
DVK

Reputation: 129383

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|

Upvotes: 4

Related Questions