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

Hello all, I'm new to perl and currenlty having an issue with a little script. I'm trying to match a variable against another variable read in from a line in a text file and replace based upon a positive match. However, I can never get the match sequence to work correclty.
#!/usr/bin/perl print "Directory path? "; chop ($_dirpath = <STDIN>); print "File extension? "; chop ($_filext = <STDIN>); print "Replace: "; chop ($_match = <STDIN>); print "By: "; chop ($_newline = <STDIN>); opendir (DH,$_dirpath) or die "Can't access directory\n"; while ($olditem = $item = readdir DH) { if ($item !~ /\.$_filext$/) { print "Skipping $item\n"; next; } $olditem =~ s/\.$_filext$/.bak/; rename "$_dirpath/$item","$_dirpath/$olditem"; open (workinfile,"$_dirpath/$olditem")or die "Can't read Work +File\n"; open (newfile, ">$_dirpath/$item")or die "Can't read new File\ +n"; while ($_linein = <workinfile>) { if ($_linein eq $_match) { printf newfile $_linein, "\n" or die "Can't write File\ +n"; printf newfile $_newline, "\n" or die "Can't write File +\n"; } else { printf newfile $_linein, "\n" or die "Can't write File +\n"; } next; } close (workinfile); close (newfile); }
Any help would be greatly appreciated!!!!!!!! Thanks In Advance! -Steve

Replies are listed 'Best First'.
Re: Perl Matching with text file
by davidrw (Prior) on Aug 17, 2005 at 18:54 UTC
    take a look at perldoc perlrun for the -i option as well as the -p and -e options. Basically you can do this directly from the command-line with perl like this:
    perl -i.bak -pe 's/foo/bar/' somedir/*.ext