Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
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
Replies are listed 'Best First'.
Re^2: Find pieces of text in a file enclosed by `@` and replace the inside
by McA (Priest) 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 romping around the Monastery: (10)
As of 2015-07-28 10:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (254 votes), past polls