coding101 has asked for the wisdom of the Perl Monks concerning the following question:

hello I am new here and I am new to PERL. I have an XML file with encoding UTF-16 I want to find and replace a string but somehow it didn't work. Can someone help me please? Any tips? Thank you very much!

Replies are listed 'Best First'.
Re: PERL newbie question
by CountZero (Bishop) on Sep 07, 2012 at 04:10 UTC
    I want to find and replace a string but somehow it didn't work.
    That is pretty vague and does not give us much to work with. Couldn't you open the file? Did nothing get found/replaced? Did the wrong things got found/replaced? Couldn't you save the results?

    Please show your code, some relevant input data and the results of your code plus any errors or warnings.

    BTW: It is Perl (the language) or perl (the program), but not PERL. That really sets you apart as a newbie. :)

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
Re: PERL newbie question
by cheekuperl (Monk) on Sep 07, 2012 at 02:39 UTC
    Any code you've written?
    Roughly, it works as follows:
    1. Open and read the file - TMTOWTDI - you can do it line by line.
    while($line=<FH>) { $line=~s/foo/baz/g; # Replace all occurrences. #Write $line to a temp file }
    2. Now rename temp file to original file.
Re: PERL newbie question
by philiprbrenan (Monk) on Sep 07, 2012 at 13:45 UTC

    This might help you get started. If you can provide the actual XML data it will be easier to help further. Please note this code is UNTESTED!

    use feature ":5.14"; use warnings FATAL => qw(all); use strict; use Data::Dump qw(dump pp); use XML::Simple; sub readUnicode($) {my ($f) = @_; open(my $F, "<:encoding(UTF-16)", $f) or die "Cannot open $f for uni +code input"; local $/ = undef; <$F>; } sub writeUnicode($$) {my ($f, $s) = @_; open(my $F, ">:encoding(UTF-16)", $f) or die "Cannot open $f for uni +code output"; say {$F} $s; } my $x = XMLin(readUnicode("some file containing XML")); $x->{foo}{bar} = "new value"; my $X = XMLout($x); writeUnicode("output file name", $X);