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

I am running the following script using data from a configuration file. For some reason unknown to me same values are returned instead of different ones as shown in the bottom. Can someone explain what I am doing wrong?
Thanks.

The config file myconfig.cfg:

CCBFile|NDM|/u1/cdunix/work/blprobr1|S${TODAY}.00?|${TODAY}CCB

The script -

#!/apps/bin/perl -w $TODAY = "20030518"; $config_file = "myconfig.cfg"; open (CONFIG, "$config_file") || die "Can't open $config_file for read +ing : $!\n"; while ( defined ($_ = <CONFIG>) ) {<br> my($job,$type,$dir,$file,$pattern) = split(/\|/,$_); my $val1 = file_eval($file); my $val2 = file_eval($pattern); print "val1 : $val1\n"; print "val2 : $val2\n"; } close(CONFIG); sub file_eval { my ($value) = @_; $match = '([0-9A-Za-z._%?#]*)(\$\{\w+\})([0-9A-Za-z._%?#]*)'; if ( $value =~ /$match/g ) { print "\nvalue is : $value\n"; ($p1,$p2,$p3) = /$match/; print "\n p1 is $p1\n"; print "\n p2 is $p2\n"; print "\n p3 is $p3\n"; $px = eval "$p2"; $filex = $p1 . $px . $p3; print "\n filex is $filex\n"; } return $filex; }
The output -
value is : S${TODAY}.00? p1 is S p2 is ${TODAY} p3 is .00? filex is S20030518.00? value is : ${TODAY}CCB p1 is S p2 is ${TODAY} p3 is .00? filex is S20030518.00? val1 : S20030518.00? val2 : S20030518.00? <- should be 20030518CCB

Replies are listed 'Best First'.
Re: Getting same output doing pattern matching
by Abigail-II (Bishop) on May 21, 2003 at 22:41 UTC
    It's the following line:
    ($p1,$p2,$p3) = /$match/;

    This matches against $_, which doesn't change between calls to file_eval. Since you have already matched, you could just do:

    ($p1, $p2, $p3) = ($1, $2, $3);

    Abigail

      Abigail,

      Thanks a lot! It worked.

Re: Getting same output doing pattern matching
by pzbagel (Chaplain) on May 22, 2003 at 06:51 UTC

    On a side note, the error checks you do on the CONFIG filehandle as you read it in are already done by perl automagically.

    #The line: while ( defined ($_ = <CONFIG>) ) #can be simplified to: while(<CONFIG>)

    When you use the <> in the conditional of a while loop, perl automatically sets the $_ variable to be the input record it read from the file. It also checks that it is defined() for you so you don't have to.

    Just a little sweet syntactic sugar for you.