in reply to Inline change to the file passed by Glob
make inline changes ... open(STDOUT, "+>csv_add_up")
Are you sure you want to do it this way? An open mode of +> clobbers the file first, I don't think that's what you want. Also you don't have error checking (as in open ... or die "$filename: $!";).
i have to use stdout redirection
Normally, you would do something like open my $out_fh, '>', $filename or die "$filename: $!"; and then print $out_fh "output\n";. Alternatively one could use select, but the disadvantage is that it redirects all print and related statements. Re-opening STDOUT is something one should do only if you know what you are doing and why. (Update: If you really needed to capture STDOUT, which I don't think is the case here, use Capture::Tiny.)
passed using Glob
Is this a requirement? (I'm asking because I wouldn't necessarily do it this way.)
Anyway, the usual way to make "inline" changes is to either open a temporary file, write to it, and then rename the temporary file over the original, or the way Perl's -i switch does it, by renaming the original and then opening a new file with the same name as the original. It's theoretically possible to do it by opening a file in read-write mode (e.g. reading the entire file into memory, seeking and truncateing the file, and writing it back out), but I have to say I personally have almost never done this because it's not safe - if the program crashes, gets killed, the machine loses power, etc., you'll lose data! While not "inline" in the strictest sense, since rename is an atomic operation on many* filesystems, it's much safer - the file will either be the original or the updated version.
Example Code: Here is a demo of the rename method, and here is a demo of a trick using $^I, which is the same as Perl's -i switch (perlrun).
Lastly, I would strongly recommend Text::CSV for CSV file operations (also install Text::CSV_XS for speed).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Inline change to the file passed by Glob
by jagtar (Initiate) on Aug 23, 2017 at 05:45 UTC | |
by poj (Abbot) on Aug 23, 2017 at 06:52 UTC | |
by Anonymous Monk on Aug 23, 2017 at 06:40 UTC |