mikeysmailbox1
asked on
Perl passing in variables to do substitution
Hi
I have a script that I am passing for example
script.pl "(.*?)_(.*?).txt" "\2_\1.txt"
in the script I am just doing.
$AA = "myfile1_100.txt";
$AA =~ s/$ARGV[0]/$ARGV[1]/g;
print "$AA\n";
How can I pass in the (.*?)_(.*").txt and the \2_\1.txt
as a substitution
If I do this it works
$AA = "myfile1_100.txt";
$AA =~ s/$ARGV[0]/\2_\1.txt/g;
print "$AA\n";
I am trying to avoid hardcoding the \2_\1.txt as the values change.
Thanks,
Mike
I have a script that I am passing for example
script.pl "(.*?)_(.*?).txt" "\2_\1.txt"
in the script I am just doing.
$AA = "myfile1_100.txt";
$AA =~ s/$ARGV[0]/$ARGV[1]/g;
print "$AA\n";
How can I pass in the (.*?)_(.*").txt and the \2_\1.txt
as a substitution
If I do this it works
$AA = "myfile1_100.txt";
$AA =~ s/$ARGV[0]/\2_\1.txt/g;
print "$AA\n";
I am trying to avoid hardcoding the \2_\1.txt as the values change.
Thanks,
Mike
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
My code doesn't have double quotes around the left hand side of the substitution:
Change this:
$BB = '"' . $options->{a} . '"';
to this:
$BB = $options->{a};
Or don't bother with $BB (as per my code) and just have this:
$AA =~ s/$options->{a}/$regex/ee;
Change this:
$BB = '"' . $options->{a} . '"';
to this:
$BB = $options->{a};
Or don't bother with $BB (as per my code) and just have this:
$AA =~ s/$options->{a}/$regex/ee;
Mike, when you say "it worked somewhat", don't you mean "it worked as is but it no longer works now that I've made changes"?
In such cases, you have to go back to what worked, and change things gradually until you see what change makes it fail.
In such cases, you have to go back to what worked, and change things gradually until you see what change makes it fail.
Thanks for the points, Mike.
It seems you can get rid of the temporary $regex variable too, like this:
$AA = $options->{c};
$AA =~ s/$options->{a}/'"' . $options->{b} . '"'/ee;
print "$AA\n";
It seems you can get rid of the temporary $regex variable too, like this:
$AA = $options->{c};
$AA =~ s/$options->{a}/'"' . $options->{b} . '"'/ee;
print "$AA\n";
...or reduce it to 2 lines:
($AA = $options->{c}) =~ s/$options->{a}/'"' . $options->{b} . '"'/ee;
print "$AA\n";
($AA = $options->{c}) =~ s/$options->{a}/'"' . $options->{b} . '"'/ee;
print "$AA\n";
ASKER
It worked somewhat.
Here is my script and input
#!/usr/bin/perl
use Getopt::Long;
$Getopt::Long::passthrough
$Getopt::Long::ignorecase=
$options={};
GetOptions($options, "-a=s", "-b=s", "-c=s");
$AA = $options->{c};
$regex = '"' . $options->{b} . '"';
$BB = '"' . $options->{a} . '"';
$AA =~ s/$BB/$regex/ee;
print "$AA\n";
Command line:
./script.pl -c="myfile1_100.txt" -a="(.*?)_(.*?).txt" -b="\$2_\$1.txt"
The output is just
myfile1_100.txt
but should be
100_myfile.txt
Not sure what is causing it to not work.
Mike