I’ve a Perl script which does the job of expanding the Unix environment variables. The script is working fine. The script is as below:
# I know this should not be typed here. This is here just for testing.
@ENV{qw(LKUP_DIR DATA_DIR CTRL_DIR MMM)} = qw(/appl1/TSS/lkup /appl1/TSS/data /appl1/TSS/ctrl Oct);
while ( <DATA> )
{
my $line=$_;
chomp $line;
$line =~ s{\$(\w+)}{ exists $ENV{$1} ? $ENV{$1} : '$'.$1 }ge;
$line =~ s{\$\{(\w+)\}}{ exists $ENV{$1} ? $ENV{$1} : '${'.$1.'}' }ge;
print "$line\n";
}
__DATA__
${LKUP_DIR}/lookup_file.txt
${CTRL_DIR}/ctrl_file_$MMMM.txt
$CTRL_DIR/ctrl_file_$MMM.txt
I want to convert this script into an one-liner, but I am not sure how handle the single quotes around the $ in the regular expression used in the script mentioned above. I tried the below, but of course it is not working:
perl -lne '$line=$_; $line =~ s{\$(\w+)}{ exists $ENV{$1} ? $ENV{$1} : '$'.$1 }ge; $line =~ s{\$\{(\w+)\}}{ exists $ENV{$1} ? $ENV{$1} : '${'.$1.'}' }ge; print "$line";' DATA.txt
Any suggestions? (I want to do this only in Perl.)
I agree with @Mat: it seems a bad idea. It will be just one line but you lose on readability. Just think that you might edit a year later and still try to understand what the one liner does.
But anyway, in Perl you can use
q/STRING/instead of'STRING'.