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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String substitution at the beginning

Status
Not open for further replies.

rob51383

Programmer
Jun 23, 2004
134
0
0
US
I have been playing with perl for a few months now and can do alot with it but these string matching / substitution things always get to me, thanks in advanced for any help. My problem:

I have a variable which can be something like:

my $var = "10 sometext, some more, and 3 more"
or
my $var = "1 sometext, some more, and 3 more"

now I have a new variable say:
$id = "1"

I want to say if the first number in $var i.e(10, 1) = $id then do something.

So what if I split the string $var at the FIRST space and assigned the number to $newvar. I think that will work but how do I code that?
 
I managed to complete it. I just used the "SPLIT" function to split $var at ' ' into a string then assigned @ARRAY[0] to $newvar.

If you know a better way to do it I am open to change.
 
You could use a regular expression:
Code:
$var =~ /^(\d*)/;
if($id == $1){...
The =~ /.../ says to match what's in the regular expression (between the slashes) with what's in $var. The regular expression says look at the the beginning of the string, ^, and find zero or more numbers, \d*. The parentheses make those numbers available in the $1 variable.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top