CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [BillKSmith] Regex search and replace: Edit Log



G_Ranger
Novice

Jul 5, 2016, 11:36 PM


Views: 2884
Re: [BillKSmith] Regex search and replace

Thanks for your answer, and for pointing out the problems in my code.
With help from the web I've managed to cobble together two options which appear to work as intended. (I tried the /s and /m switches, but this seems to do the job.)
The first uses Path::Tiny and writes directly into the file, the second uses a subroutine to read in the whole file, then writes output into another file. I'm not sure which is advisable... and I still ultimately need to set up the different terms as command-line arguments.

First option:

Code
use strict; 
use warnings;
use Path::Tiny qw(path);

my $filename = 'sentence';
my $file = path($filename);
my $data = $file->slurp_utf8;
$data =~ s/en\tPRO:PER\ten\n(?=.*ant\b)/en\tPRP\ten\n/g;
$file->spew_utf8( $data );


Second option:

Code
use strict; 
use warnings;
my $filename = 'sentence';
my $out_file = 'output';
my $data = read_file($filename);
$data =~ s/en\tPRO:PER\ten\n(?=.*ant\b)/en\tPRP\ten\n/g;
open my $out, '>:encoding(UTF-8)', $out_file or die "Could not open '$out_file' for writing $!";;
print $out $data;
exit;

sub read_file {
my ($filename) = @_;
open my $in, '<:encoding(UTF-8)', $filename or die "Could not open '$filename' for reading $!";
local $/ = undef;
my $all = <$in>;
close $in;
return $all;
}



(This post was edited by G_Ranger on Jul 6, 2016, 2:28 AM)


Edit Log:
Post edited by G_Ranger (Novice) on Jul 6, 2016, 2:28 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives