Pages

Friday, February 8, 2013

Perl question

Ok, so I want to replace a lot of... we'll call them "words" but in fact they're combinations of letters and numbers.

And I have, a hash which is composed of pairs such that the key is "the thing I want to replace" and the value is "the thing I want to replace it with".  Other than the words being swapped out I want to copy the original exactly so I used the copy function:

use File::Copy;
copy(original, output file)

-

Which seemed like a good place to start and works just fine.

Here's the problem, how the hell do I replace the words in the copied file?

I've tried looking things up, but whatever I try either throws errors left and right, or does nothing to the file.

This is what I think I want to do:

foreach my $hash (keys %hash) {
  Replace every $hash in the output file with %hash{$hash}
  (if I wrote that wrong, replace every instance of the key with the associated value)
}

Or, failing that, go through the output file word by word and if (exists %hash{word}) replace that word with the value associated with it.

Either way.

My problem is that in spite of looking  things up, or at least trying to, everything I do leaves the output file untouched.  It remains a flawless copy of the original.

4 comments:

  1. Did you remember to write out the file again when you were done with it? The changes are probably being done in memory. You want to ensure you have lines like the following:

    open (MYFILE, '>>data.txt');
    print MYFILE "Bob\n";
    close (MYFILE);

    ReplyDelete
  2. File::Copy is just for copying files, not modifying them. What I'd suggest is to split it into stages:

    - read each line into a scalar variable
    - modify that variable
    - write it out

    I wrote some code but blogspot isn't letting me post it. I'll drop you email.

    ReplyDelete
    Replies
    1. File::Copy is just for copying files, not modifying them.

      I only wanted that for copying the file. I wanted a copy of the original to modify, when I got the modifying files bit, while leaving the original untouched.

      What I couldn't figure out was how to get to the modifying files bit.

      If I understand what you're saying (I will check my email) I did consider that but it seemed like it would be simpler to start with a full file and then make a series of modifications to it. Guess I was wrong.

      Delete
    2. Oh, I see. Yeah, it's easier to read in the data, modify stuff, and write out to a new file, rather than copying and then modifying in place.

      Delete