in reply to Change a line in a file

As $line is an alias for the subsequent elements in the array, you can replace
foreach my $line (@array) { if ($line =~ /^JOB=/) { $array[$counter] = "RMT=$file\n"; } $counter++; }
by
foreach my $line (@array) { $line =~ s/^JOB=/RMT=$file\n/; }
or even shorter by
s/^JOB=/RMT=$file\n/ for @array;

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: Change a line in a file
by rightfield (Sexton) on Aug 23, 2008 at 23:23 UTC
    Thank you CountZero. This gave me the best solution. Turns out I was trying to open the file incorrectly as "netbpa" astutely noticed but in the end I did not have to open the file the second time. I took your shortest suggestion and used it on the string $trace as follows:
    sub t_write { my($file, $aOrder) = @_; my($trace) = $aOrder->{trace_file_data}; if (!defined($trace) || length($trace) == 0) { print "No trace file.\n"; return; } $trace =~ s/JOB=.*/RMT=$file/; open(F, "> $file\0") or die "Can't create trace-file $file ($!)\n" +; print F $trace; close(F); #make a comment that this was done print "Trace file: $file\n"; }
    This solution added only one line to the original subroutine! Thank you. Warm regards,