partymeeple has asked for the wisdom of the Perl Monks concerning the following question:

hello again keepers of the code.
can somone tell me a better way to do this? it does not feel "perly" enough.
$_ = $value; $value = m/(\d+)/;
i tried.
$value =~ /(\d+)/;
but i obviously do not fully understand the " =~ " operator..
bows low...
beware the farmers.

Replies are listed 'Best First'.
Re: it seems i don't understand =~
by ikegami (Patriarch) on Mar 30, 2009 at 02:22 UTC

    Even your supposedly working version doesn't work. The match needs to be in list context (as created by the parens below) for the the match operator returns a list of the captured values.

    =~ is used to specify what value the match operator operates on. It doesn't affect the returned value.

    ($value) = $value =~ /(\d+)/;
Re: it seems i don't understand =~
by partymeeple (Novice) on Mar 30, 2009 at 03:19 UTC
    thanks ikegami. i don't get the " won't compile comments".. the two lines fix a bug in the script which "seems" to be working ok on my host now..?? though i can now see it's not working the way i want it too. ~frowns~ i'm curious why would the code run on a server and return errors on your machines? it worked on my box ~shruggs~
    beware the farmers.

      thanks ikegami. i don't get the " won't compile comments"..

      >type 754047.pl $value =~ s/\D//g; $value =~ $1 if( $value =~ /(\d+)/ ){ $value =~ $1 } else { undef $value; } >perl -c 754047.pl syntax error at 754047.pl line 3, near "){" 754047.pl had compilation errors.

      the two lines fix a bug in the script which "seems" to be working ok on my host now..??

      Seems is the operative word

      my $value = "abc456def"; $_ = $value; $value = m/(\d+)/; print "$value\n"; # Prints 1, not 456

      Fix:

      my $value = "abc456def"; $_ = $value; ($value) = m/(\d+)/; print "$value\n"; # Prints 456

      A more elegant version that doesn't clobber a global:

      my $value = "abc456def"; ($value) = $value =~ m/(\d+)/; print "$value\n"; # Prints 456
        oh.. i get it.. i thought the not working code was referring to my 2 lines, not the other segment (i didn't bother to look at it as i wanted a shorter model).

        yes my code seemed to work. but actually was not. your suggestion fixed it perfectly.

        thanks again.

        beware the farmers.
Re: it seems i don't understand =~
by Anonymous Monk on Mar 30, 2009 at 02:24 UTC
    $value =~ s/\D//g; $value =~ $1 if( $value =~ /(\d+)/ ){ $value =~ $1 } else { undef $value; }
      That doesn't even compile, among other problems.
      A reply falls below the community's threshold of quality. You may see it by logging in.