Re: getting a number out of a string....




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

.



Relevant Pages

  • Re: to () or not to (), that is the question.
    ... depending on whether it was called in scalar context or list context. ... In scalar context, a pattern match returns whether or not it was able to ... If the pattern match has the /g modifier on it, the context changes how it behaves as well. ...
    (perl.beginners)
  • Re: to () or not to (), that is the question.
    ... depending on whether it was called in scalar context or list context. ... In scalar context, a pattern match returns whether or not it was able to ... If the pattern match has the /g modifier on it, the context changes how it behaves as well. ...
    (perl.beginners)
  • Re: to () or not to (), that is the question.
    ... A pattern match returns different values ... > depending on whether it was called in scalar context or list context. ...
    (perl.beginners)
  • Re: regex for matching repeated strings
    ... \1 within a pattern match means exactly what $1 will mean when the ... by the newline, and then checks to see if the next thing after that is ... Since the second instance was of the .*\n was not ...
    (perl.beginners)
  • Re: Count number of times matched
    ... So I will have matched "sentence" twice and I want to record this. ... Assigning the return value of the pattern match to an array means that the pattern match is executed in LIST context, ...
    (perl.beginners)