swapnil
swapnil

Reputation: 77

What does Perl's substr do?

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

$convar = substr($var,0,index(".",$var));

Upvotes: 1

Views: 2646

Answers (5)

Alex Brown
Alex Brown

Reputation: 42872

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.

Upvotes: 0

Ether
Ether

Reputation: 53966

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

Upvotes: 0

Charles Ma
Charles Ma

Reputation: 49171

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

Upvotes: 0

aks
aks

Reputation: 25357

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.

Upvotes: 2

Brian Agnew
Brian Agnew

Reputation: 272277

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"

Upvotes: 5

Related Questions