Bootstrap FreeKB - Perl (Scripting) - Read and write to the same file
Perl (Scripting) - Read and write to the same file

Updated:   |  Perl (Scripting) articles

Perl's approach to reading and writing to the same file is to store the current file into an array or a temporary file, to update the array or temporary file, and to then replace the original file with the updated array or temporary file. I typically prefer to store the current file in an array instead of a temporary file.

 


Array

my $file = "example.txt";
my @array;

# Open the file for reading
if (open IN, "<", $file) {
  # Load the content of the file into an array
  @array = <IN>;

  # Close the file handle
  close IN;
}
else {
  print "failed to open $file \n";
  exit 1;
}

# Open the file for writing
if (open OUT, ">", $file) {
  # Loop through each line in @array
  foreach my $line (@array) {

    # THIS IS WHERE YOU WOULD MAKE YOUR MODIFICATIONS TO $line
    # THIS IS JUST AN EXAMPLE OF REPLACING "old" WITH "new"
    $line =~ s|old|new|;

    # Write each line in the array to the file
    print OUT $line;
  }

  # Close the file
  close OUT;
}
else {
  print "failed to open $file \n";
  exit 1;
}

 


Temporary file

my $file = "example.txt";

# Open the original file
if (open IN, "<", $file) {
  print "successfully opened $file \n";
}
else {
  print "failed to open $file \n";
  exit 1;
}

# Create a tmp file
if (open OUT, ">", "${file}.tmp") {
  print "successfully opened "${file}.tmp" \n";
}
else {
  print "failed to open "${file}.tmp" \n";
  exit 1;
}

# Loop through each line in the original file
while (my $line = <IN>) {

  # THIS IS WHERE YOU WOULD MAKE YOUR MODIFICATIONS TO $line
  # THIS IS JUST AN EXAMPLE OF REPLACING "OLD" WITH "NEW"
  $line =~ s|old|new|;

  # Write each line to the tmp file
  print OUT $line;
}

# Close both files
close IN;
close OUT;

# Delete the original file
unlink($file);

# Rename the tmp file to have the original file name
rename("${file}.tmp", $file);

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter d2634a in the box below so that we can be sure you are a human.