Dear Members of the Perl Community,

I am new to this forum and quite new to programming. I picked up Perl to facilitate certain annoying tasks such as the following:

A given folder x contains a number of files.

The aim of the script is to open each file in the folder and replace the strings as shown in the code.

So far, the script opens the folder and reads the files into the array. The files are printed to my command line.

However, something seems to be wrong in the substitution section, since the files are not touched (same date of creation, etc.) and apparently no replacement has been effected and no backup files have been created, either.

I would be delighted if you could shed some light on my code, since I am not getting any error messages.

$^I = ".bak"; my $directory = "c:/temp/"; opendir( DIR, $directory ) or die "Unable to open dir!"; my @xml_files = grep( /\.xml$/, readdir(DIR) ); say "files found"; print "\n\n"; say for @xml_files; print "\n\n"; say "Replacing strings"; print "\n\n"; foreach my $file (@xml_files) { open( IN, "+>", $file ) or die $!; while( <IN> ){ $_ =~ s{&}{&amp;}g; $_ =~ s{&amp;amp;}{&amp;}g; $_ =~ s{\s>\s}{&gt;}g; $_ =~ s{\s<\s}{&lt;}g; print IN $file; } close ( IN ); } closedir (DIR); say for @xml_files;
Thanks a mil in advance for your support. C.

In reply to search and replace strings in different files in a directory by PitifulProgrammer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.