0

In my perl script, I have a string variable which has '' in it. I have to replace it with a proper date like '20150101'. I tried the below but it expects the variable as file. Can you please point out what's wrong here?

#!/usr/bin/perl

my $name="FILE_NAME_<DATE>.txt";
my $findDT="<DATE>";
my $dt="20150101";

my $realFileName=~`sed "s/$findDT/$dt/g" $name `;

print $name;
print $realFileName;
2
  • 3
    Ah, what a beautiful lack of use strict; use warnings; on this Wednesday morning. Commented Jul 29, 2015 at 7:53
  • 2
    ... I don't get why you are doing these things. Why have those extra varaibles? Why use break out to using a shell to run a sed command... that takes Perl regex when you using Perl already. Why even use Perl for this when you have the sed command to do what you want? Commented Jul 29, 2015 at 7:59

2 Answers 2

3

You don't need sed, which works on the content of a file. You can do this:

#!/usr/bin/perl
use strict;
use warnings;

my $name="FILE_NAME_<DATE>.txt";
my $findDT="<DATE>";
my $dt="20150101";

# First make a copy of your original variable
my $realFileName = $name;

# Then, replace the variable
$realFileName =~ s/$findDT/$dt/;

print "$name\n";
print "$realFileName\n";

As noted in a comment, remember to always use strict; and use warnings;. They cost nothing and help a lot!

Sign up to request clarification or add additional context in comments.

1 Comment

accidentally missed the 'use' statements in this test script. Thanks a lot.
3

I don't know why you are using sed. Change your script to this.

r - perform non-destructive substitution and return the new value

Check here

#!/usr/bin/perl
use strict;
use warnings;

my $name="FILE_NAME_<DATE>.txt";
my $findDT="<DATE>";
my $dt="20150101";

my $changedFileName = $name=~ s/$findDT/$dt/r;

print "Before Change: $name \n";
print "After Change: $changedFileName \n";

1 Comment

Agreed - Either use Perl or Unix Shell to do things like this - Not both. Also, doing it in Perl will make it cross-platform and will run on Windows too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.