CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [joseph4325] substitution question: Edit Log



2teez
Novice

Jun 11, 2013, 11:59 PM


Views: 649
Re: [joseph4325] substitution question


Quote
Why are you opening $filename four times where you really need to open once the input file and once the output file?

Good question to ask...

Quote
This is what i'm trying to fix. My problem is in 1 condition i need it to overwrite an existing line, in a separate condition i need to append to the file, and in the 3rd i'm reading from the file

Under which condition are you doing the in place editing? And under which are you writing out?

Quote
or is there some way i can append and overwrite in the same file open?

FishMonger has given you one way to do it. You can as well use '-i' on the CLI or '$^I' from your script to do in-place editing. Please see http://perldoc.perl.org/perlrun.html#Command-Switches.
Moreover, the code below could also help.

Code
use warnings; 
use strict;

my $filename = 'test.txt';

open my $fh2, '>', 'output.txt' or die "can't open file: $!";
open my $fh, '<', $filename or die "can't open file: $!";

while (<$fh>) {
chomp;
if (/(.+?)(-?\d+?)$/) {
print $fh2 $2 <= 0 ? qq[$1 1 $/] : qq[$1 0 $/];
}
elsif (/(-?\d+?)$/) {
print $fh2 $1 <= 0 ? qq[string, 1$/] : qq[string, 0$/];
}
}

close $fh or die $!;
close $fh2 or die $!;



(This post was edited by 2teez on Jun 12, 2013, 12:20 AM)


Edit Log:
Post edited by 2teez (Novice) on Jun 12, 2013, 12:01 AM
Post edited by 2teez (Novice) on Jun 12, 2013, 12:03 AM
Post edited by 2teez (Novice) on Jun 12, 2013, 12:20 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives