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

Dear Monks,
I need some help in this situation, when looking for opened dialup connections on a cisco router. I got this warning.
($totcalls += $layer3) =~ s/^[\s+]([0-9]) Active.*/$1/;
 ....and the warning....
Argument "2 Active Layer 3 Call(s)" isn't numeric in addition (+) at ...
there is some way to do a "cast to int" on the regex output, before assign the value to $totcalls? To get rid of the warning?
thanks for the wisdom,
Marcelo
  • Comment on avoid warnings in Copying and Substituting Simultaneously

Replies are listed 'Best First'.
Re: avoid warnings in Copying and Substituting Simultaneously
by ccn (Vicar) on Oct 22, 2008 at 17:17 UTC
    ($totcalls += [split / /, $layer3]->[0]) =~ s/^\s+(0-9) Active.*/$1/;
      thanks :)
Re: avoid warnings in Copying and Substituting Simultaneously
by ikegami (Patriarch) on Oct 22, 2008 at 17:25 UTC
    $totcalls += $layer3 =~ /^([0-9]*)/ && $1;

    or better yet

    $totcalls += do { no warnings 'numeric'; 0+$layer3 };

    Your s/// will never match because it's modifying $totcalls after the sum-assign (i.e when it contains a number).

Re: avoid warnings in Copying and Substituting Simultaneously
by jhourcle (Prior) on Oct 22, 2008 at 17:35 UTC
    ($totcalls += $layer3) =~ s/^[\s+]([0-9]) Active.*/$1/;

    I think you're confused with your order of operations ... you code will do the addition first, then the substitution (which fails, because it's operating on an integer)

    ccn's solution will get rid of the warning by fixing the addition, but there's then no reason to do the substitution. I'm guessing you were probably trying to do:

    $totcalls += [ $layer3 =~ m/^\s*([0-9]+) Active/ ]->[0];

    ... which has the advantage that it'll throw some warnings when there's bad values in $layer3:

      $totcalls += [ $layer3 =~ m/^\s*([0-9]+) Active/ ]->[0];
      needlessly creates an array and a reference. Use
      $totcalls += ( $layer3 =~ m/^\s*([0-9]+) Active/ )[0];

        And that needlessly performs a regexp. And since perl still has to do the ascii to numeric conversion, you might as well do it right away.
        { no warnings 'numeric'; $totcalls += $layer3; }
        And that will even work if $layer3 starts with a negative number or a float. It's a design feature that Perl works this way.