
7stud
Enthusiast
Jan 16, 2013, 12:37 PM
Post #4 of 8
(1786 views)
|
Re: [madonion55] Copy and change contents of one file to another
[In reply to]
|
Can't Post
|
|
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.
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.
$ cat results.txt Variable1 = 10 Variable2 = 20 Variable3 = 30
(This post was edited by 7stud on Jan 16, 2013, 12:57 PM)
|