Home > Net >  Perl: Adding text before filename extension?
Perl: Adding text before filename extension?

Time:09-17

How would I go about appending text to a filename before the extension?

For example,

open my $in, '<', $my_file or die $!;

open my $out, '>',"$my_file" or die $!;

$my_file looks like this:

/this/is/my/directory/blahblah.txt/ 

I want to append it in the output like this:

/this/is/my/directory/blahblah_new.txt
or 
new_blahblah.txt 

Hope thats an okay explanation! Thank you.

CodePudding user response:

Use regex substitution like so:

open my $in, '<', $my_file or die "Cannot open $my_file for reading: $!";
( my $out_file = $my_file ) =~ s{([.]txt)$}{_new$1};
open my $out, '>', $out_file or die "Cannot open $out_file for writing: $!";
  •  Tags:  
  • perl
  • Related