If this is a command-line tool, have you considered simply using sed(1)? You seem to be reimplementing it.

If there is some frontend interface here more complex (like a CGI script, other Web toolkit, or a GUI, like Tk) then you are mostly on the right track, but it would be far better to write to a new file and then use rename to replace the existing file after the process is complete. Something like: (untested)

use strict; use warnings; sub toy_sed_on_file { my $pattern = shift; my $replacement = shift; my $file = shift; my $count = 0; open my $in, '<', $file or die "open $file: $!"; open my $out, '>', $file.$$ or die "open output ${file}$$: $!"; while (<$in>) { $count += s/$pattern/$replacement/g; # does nothing if m/$pattern +/ would not match print $out $_; } close $in or die "close $file: $!"; close $out or die "close output ${file}$$: $!"; if ($count > 0) { rename $file.$$, $file or die "replace input file: + $!" } else { unlink $file.$$ or die "remove output file: $!" } return $count; }

Note that the s/// pattern-match-replacement operator returns the number of matches found, so there is no need in this program to separately count the matches.

Also note that using $$ (the process ID) to construct temporary filenames is only suitable in a secure and trusted environment but is very simple for a demonstration; you should probably use File::Temp and the DIR option to tempfile to ensure that the output file is created in the same directory as the input file. (The rename builtin can only be guaranteed (barring "disk full" and other errors) to work within the same directory.)


In reply to Re: user input Regular Expression by jcb
in thread user input Regular Expression by Saved

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.