tags:

views:

58

answers:

4

#!/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?

+3  A: 

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|
DVK
+1  A: 

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

ivancho
@ivancho - good point, though you're floating towards "and now you have two problems" area :)
DVK
@DVK no, no, see how I carefully sidestepped the regular expression there
ivancho
Meh... mere technicality... you were there in spirit ;)
DVK
+2  A: 

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

ysth
+2  A: 

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