views:

611

answers:

5

My variable $var has the form 'abc.de'. What does this substr exactly do in this statement:

$convar = substr($var,0,index(".",$var));
+5  A: 

index() finds one string within another and returns the index or position of that string.

substr() will return the substring of a string between 2 positions (starting at 0).

Looking at the above, I suspect the index method is being used incorrectly (since its definition is index STR, SUBSTR), and it should be

index($var, ".")

to find the '.' within 'abc.de' and determine a substring of "abc.de"

Brian Agnew
ah, so the original code is an elegant way to say chop($convar=$var); :)
ysth
Inelegant, surely :-)
Brian Agnew
The "smart" thing about substr() is that it can also be used as a lvalue.
Beano
+2  A: 

The substr usage implied here is -

substr EXPR,OFFSET,LENGTH

Since the offset is 0, the operation returns the string upto but not including the first '.' position (as returned by index(".", $var)) into $convar.

Have a look at the substr and index functions in perldoc to clarify matters further.

muteW
A: 

The Perl substr function has format:

substr [string], [offset], [length]

which returns the string from the index offset to the index offset+length

index has format:

index [str], [substr]

which returns the index of the first occurrence of substr in str.

so substr('abc.de', 0, index(".", $var)); would return the substring starting at index 0 (i.e. 'a') up to the number of characters to the first occurrence of the string "."

So $convar will have "abc" in the example you have

edit: damn, people are too fast :P edit2: and Brian is right about index being used incorrectly

Charles Ma
A: 

Why not run it and find out?

#!/usr/bin/perl
my $var = $ARGV[0];
my $index = index(".",$var);

print "index is $index.\n";

my $convar = substr($var, 0, $index);
print "convar is $convar.\n";

Run that on a bunch of words and see what happens.

Also, you may want to type:

perldoc -f index
perldoc -f substr
Ether
A: 

Fabulously, you can write data into a substring using substr as the left hand side of an assignment:

$ perl -e '$a="perl sucks!", substr($a,5,5)="kicks ass"; print $a'
perl kicks ass!

You don't even need to stick to the same length - the string will expand to fit.

Technically, this is known as using substr as an lvalue.

Alex Brown