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: [madonion55] Copy and change contents of one file to another: Edit Log



7stud
Enthusiast

Jan 16, 2013, 12:37 PM


Views: 766
Re: [madonion55] Copy and change contents of one file to another

In modern perl, you don't use bareword filehandles.
In modern perl, you use the 3-arg form of open.
In modern perl, you output the system error message if open() fails.
In modern perl, you start every program with the equivalent of the first three lines below.


Code
use strict; 
use warnings;
use 5.012;

my %new_values_for = (
Var1 => ['Variable1', 10],
Var2 => ['Variable2', 20],
Var3 => ['Variable3', 30],
);

open my $OUTFILE, ">", 'results.txt'
or die "Couldn't open results.txt: $!";

for my $line (<DATA>) { #The DATA filehandle reads any lines after __DATA__

if ($line =~ /(\w+) \s* = /xms) {
my $var_name = $1;

#Check if there is an entry in the hash for the current var name:
if (my $values = $new_values_for{$var_name}) {
my($new_var_name, $new_value) = @{$values};

say $OUTFILE "$new_var_name = $new_value";

delete $new_values_for{$var_name};
}
else { #Variable found, but no new values are specified
print $OUTFILE $line;
}
}
}


for my $key (keys %new_values_for) {
my($var_name, $value) = @{$new_values_for{$key}};
say $OUTFILE "$var_name = $value";
}

close $OUTFILE;



__DATA__
Var1 = 1
junk here
Var2 = 2

Note that the output from that last loop will be in random order.


Code
$ cat results.txt 

Variable1 = 10
Variable2 = 20
Variable3 = 30



(This post was edited by 7stud on Jan 16, 2013, 12:57 PM)


Edit Log:
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:37 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:38 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:38 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:40 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:41 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:43 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:44 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:45 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:47 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:50 PM
Post edited by 7stud (Enthusiast) on Jan 16, 2013, 12:57 PM


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

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