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

i have simple code that will check for a matching string. if the string is found i need to substitute it with a new string. how do i accomplish it? i am a begginer. thank you.
... ... ... $nDateStamp = $month . $day . $year; $filename = '17000_DM161_082511.dat'; if (index($filename,$tDateStamp) != -1) { print "found\n"; # substitute the 082511 with the $nDateStamp # results in '17000_DM161_082411.dat }

Replies are listed 'Best First'.
Re: variable value substitution
by toolic (Bishop) on Aug 25, 2011 at 16:27 UTC
    Use the substitution operator:
    use warnings; use strict; my $nDateStamp = '082411'; my $filename = '17000_DM161_082511.dat'; print "$filename\n"; $filename =~ s/082511/$nDateStamp/; print "$filename\n"; __END__ 17000_DM161_082511.dat 17000_DM161_082411.dat
      thanks so much that works.
Re: variable value substitution
by zentara (Cardinal) on Aug 25, 2011 at 16:33 UTC
    Do you need to rename the file too? If so, in addition to what toolic showed
    rename($filename, $new_filename)
    Just changing the string, won't actually change the name of the .dat file on the disk.

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
Re: variable value substitution
by ww (Archbishop) on Aug 25, 2011 at 19:43 UTC
Re: variable value substitution
by ajose (Acolyte) on Aug 25, 2011 at 17:58 UTC

    For substitution, you can use ~s///. This will just substitute the file date with your date. Also the result has a date 082411. I assume that $nDateStamp holds this value. And $tDateStamp holds 082511.

    $nDateStamp = '082411'; $tDateStamp = '082511'; $filename = '17000_DM161_082511.dat'; if (index($filename,$tDateStamp) != -1) { $filename =~ s/$tDateStamp/$nDateStamp/; print "found\n$filename\n"; }

    Or in a better way:

    $nDateStamp = '082411'; $tDateStamp = '082511'; $filename = '17000_DM161_082511.dat'; if ( $filename =~ s/$tDateStamp/$nDateStamp/) { print "found\n$filename\n"; }