Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expression VS the "split" function 2

Status
Not open for further replies.

keak

Programmer
Sep 12, 2005
247
CA
Hi there,
I have a variable of the following format

$test="value1|value2|value3|value4.....";
and what I want to do is to have value1 and value3 assigned to new variables;
If using split, I have something like
@temps = split (/\|/, $test);
$var1 = temps[0];
$var2 = temps[2];

My question is, is it possible for me to do this split in a one liner? Also, if we consider speed (resource used), will it be better if I used a regular expression statement to perform this task? or is the split function more efficient?

Thanks!

 
If work can be done by split(), then it is recommended to stick on that i.e.split(), as it does not invoke regular expression engine thus can be faster.

--------------------------------------------------------------------------
I never set a goal because u never know whats going to happen tommorow.
 
the first argument to split is a regular expression, so I would assume it does use the regexp engine.
 
Yes it is true in this particular case, but generally when regex is not used in split it is faster.

E.g.

Code:
$test = "a,b" ;
#Using split
my($a,$b) = split(",",$test) ;
#Using Regex
$test =~ /^(\w),(\w)$/ ;



--------------------------------------------------------------------------
I never set a goal because u never know whats going to happen tommorow.
 
Kevin
Ok,I understood your point.



--------------------------------------------------------------------------
I never set a goal because u never know whats going to happen tommorow.
 
Or, more tersely:
Code:
my ($var1,$var2) = ( split (/\|/, $test) )[0,2];
 
Nice one ishnid, didn't know you could do that to a split and tack the indexs to be assigned on the end.

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
Thanks. The split() function returns a list. The [0,2,] is getting a slice of that list, just like you'd get an array slice from an array.
 
Sweet, thanks for the help guys.
The array assignment link split function is defnitely something new I didn't know.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top