in reply to Evaluating a regex replacement value

Hai, Try this,

use strict; my $value=5; while (my $line=<DATA>){ $line =~ s/<:KEYWORD:([^:>]*)\:?>/my $dum=$1; my $val; if ($dum) { $va +l = $value * $dum }else{ $val=$value} $val/e; print $line, "\n"; } __DATA__ <:KEYWORD:4:> <:KEYWORD:5:> <:KEYWORD:> <:KEYWORD:9:>

Regards,
Velusamy R.

Replies are listed 'Best First'.
Re^2: Evaluating a regex replacement value
by davidrw (Prior) on Oct 05, 2005 at 13:02 UTC
    You can rewrite
    my $dum=$1; my $val; if ($dum) { $val = $value * $dum }else{ $val=$val +ue} $val
    To be ($1 != 0)? ($value * $1) : $value like prasadbabu had it, or really it can just be boiled down to:
    $value * ($1 || 1)
    (Assuming that $value is alway numeric) No need for a temp variable or the explicit if/else.

    also, since you're not chomp'ing $line, that "\n" in your print line is going to going to double-space the output...
      Thanks :)

      This is a nice, clean option and is what I've settled on.
      $line =~ s/<:KEYWORD:([^:>]*):?>/int($value * ($1 || 1))/e;
      The not chomp'ing was never an issue, as I wasn't explicity adding newlines to the output.

      heh... I've just been browsing through my copy of Perl Best Practices, and realised that I should abstract my KEYWORD<=>$values pairs into a lookup hash.... so I'm off to do that now :)

      Thanks again,
      --Darren