in reply to Print text on the same line after match

I usually create a new file with its new name rather than renaming the original file and I compare new and old to make sure nothing has gone wrong before unlinking the original. Perhaps an over-complication but a background in systems administration, where trashing a file could bring down a service, has instilled caution.

use strict; use warnings; use POSIX qw{ strftime }; use Digest::MD5; my $origFile = q{cr835.txt}; open my $origFH, q{<}, $origFile or die qq{open: < $origFile: $!\n}; my $line = <$origFH>; close $origFH or die qq{close: < $origFile: $!\n}; my $payeeID; if ( $line =~ m{INC\*XX\*(\d+)} ) { $payeeID = $1; } else { die qq{Could not match payee ID\n}; } my $newFile = qq{cr835-} . $payeeID . strftime q{-processed_%Y-%m-%d_%H-%M.txt}, localtime; open my $newFH, q{>}, $newFile or die qq{open: > $newFile: $!\n}; print $newFH $line; close $newFH or die qq{close: > $newFile: $!\n}; my $origMD5 = Digest::MD5 ->new() ->addfile( do { open my $fh, q{<}, $origFile or die $!; $fh; } ) ->hexdigest(); my $newMD5 = Digest::MD5 ->new() ->addfile( do { open my $fh, q{<}, $newFile or die $!; $fh; } ) ->hexdigest(); if ( $origMD5 eq $newMD5 ) { unlink $origFile or die qq{unlink: $origFile: $!\n}; } else { die qq{Original and new files differ\n}; }

I hope this is helpful.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Print text on the same line after match
by BillKSmith (Monsignor) on Dec 15, 2018 at 03:48 UTC
    The command switch /i accomplishes almost the same thing. Ref: Command Switches. Note that the OP is already using /n.
    Bill
      The command switch /i accomplishes almost the same thing

      I would say it might accomplish something vaguely similar but it doesn't satisfy the main requirement of the OP's script which is to rename the file. Since the content of the original file is not being changed in any way but is only being queried to provide the new filename I don't think that in-place editing using -p is appropriate. All it can do here is write exactly the same content to the same filename, with the possibility of leaving an identical backup file behind as well. Also, as far as I can see the OP is only using -n in the unnecessary system call inside the script to the Perl one-liner; we only see part of the main script from the look of it.

      Cheers,

      JohnGG