Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: how to in-place update a dataset?

by educated_foo (Vicar)
on Mar 14, 2013 at 02:24 UTC ( [id://1023341]=note: print w/replies, xml ) Need Help??


in reply to how to in-place update a dataset?

The standard approach is to write the new contents to UpdatedFile, then rename it to RawFile after you're done. That way if something goes wrong, you still have the original file.

Replies are listed 'Best First'.
Re^2: how to in-place update a dataset?
by littlewenwen (Novice) on Mar 14, 2013 at 02:55 UTC

    Thank you. I am just wondering if the in-line update could be done. As I am still learning perl, I hope to take this opportunity to learn more.

    Again, thank you for your help.

      Hello littlewenwen, and welcome to the Monastery!

      Yes, you can do in-line updates using the standard Tie::File module:

      #! perl use strict; use warnings; use Tie::File; my $filename = 'RawFile.txt'; tie my @lines, 'Tie::File', $filename or die "Cannot tie file '$filena +me': $!"; for my $i (0 .. $#lines) { my @fields = split /\t/, $lines[$i], -1; @fields = map { $_ eq '' ? 'Missing' : $_ } @fields; $lines[$i] = join("\t", @fields); } untie @lines;

      Output in RawFile.txt:

      abcd 123 456 defg cdefg 23 Missing as Missing 345 235 Missing xsd Missing swe Missing

      Hope that helps,

      Update 1: Added -1 as LIMIT argument to split to get trailing empty fields.

      Update 2: Added final “Missing” to output; the final tab was missing from my input file on line 4. Thanks to kcott for the heads-up.

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

        Note, though, that Tie::File will probably have to rewrite the remainder of your file every time you change a line. It's clever, but probably not the right way to do what you want.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1023341]
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: (6)
As of 2024-04-19 03:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found