Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

by daxim (Curate)
on Mar 08, 2013 at 12:15 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1022407]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-04-19 20:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found