Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: user input Regular Expression

by jcb (Parson)
on Dec 14, 2020 at 01:03 UTC ( [id://11125145]=note: print w/replies, xml ) Need Help??


in reply to user input Regular Expression

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.)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11125145]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (1)
As of 2024-04-25 03:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found