Re: getting a number out of a string....
- From: "Paul Lalli" <mritty@xxxxxxxxx>
- Date: 28 Dec 2005 17:34:29 -0800
David Gilden wrote:
> Greetings,
>
> How does one just get the number part out of a string?
>
> The script below just prints 1.
>
> #!/usr/bin/perl
>
> @str = ('Gambia001.tiff','Gambia0021.tiff','Gambia031.tiff','Gambia035.tiff') ;
>
> foreach $str (@str) {
> $num = ($str =~ /\d+/);
You are running a pattern match in a scalar context. In a scalar
context, the mattern match simply returns 1 or "" (true or false)
depending on whether or not the pattern match succeeded.
You have several options:
(1)Capture what you want to match, and refer to it later:
if ($str =~ /(\d+)/){
$num = $1;
# . . .
}
(2) Call the pattern match in list context, matching globally:
($num) = ($str =~ /\d+/g);
(3) Call the pattern match in list context, and capture what you want
to match:
($num) = ($str =~ /(\d+)/);
This is all explained in detail in:
perldoc perlop
perldoc perlretut
perldoc perlre
perldoc perlreref
Paul Lalli
.
- References:
- getting a number out of a string....
- From: David Gilden
- getting a number out of a string....
- Prev by Date: Re: getting a number out of a string....
- Next by Date: Re: Each char / letter --> array from string value
- Previous by thread: Re: getting a number out of a string....
- Index(es):
Relevant Pages
|