Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Find pieces of text in a file enclosed by `@` and replace the inside

by daxim (Chaplain)
on Mar 08, 2013 at 12:15 UTC ( #1022407=note: print w/ replies, xml ) Need Help??


in reply to Find pieces of text in a file enclosed by `@` and replace the inside

The substitution operator is powerful. I'll let the regex engine do the parsing/splitting work.

use utf8;
use strict;
use warnings FATAL => 'all';
use Data::Munge qw(list2re);
use File::Slurp qw(read_file write_file);

my %tr = (
    a => 'а',
    b => 'б',
    c => 'ц',
    A => 'А',
    B => 'Б',
    C => 'Ц',
);
my $key = list2re keys %tr;

my $text = read_file('test.txt', { binmode => ':encoding(UTF-8)' });

$text =~ s{
    @       # fragment start
    ([^@]+) # capture characters inside (all except @)
    @       # fragment end
}{
    my $fragment = $1;
    $fragment =~ s{
        ($key)
    }{
        $tr{$1}
    }egmsx;
    $fragment;
}egmsx;

write_file('output.txt', { binmode => ':encoding(UTF-8)' }, $text);


Comment on Re: Find pieces of text in a file enclosed by `@` and replace the inside
Re^2: Find pieces of text in a file enclosed by `@` and replace the inside
by McA (Curate) on Mar 08, 2013 at 12:28 UTC

    I give a ++ for this very nice piece of code. This one could be in a book "Learning Perl: The clean and nice way".

    IMHO why: use good modules, format code concise, build nice regexes with comments.

    Aaaahh, this code makes me happy... ;-)

    Best regards
    McA

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2014-09-16 05:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (156 votes), past polls