How to evaluate shell variables in a string?

In my Perl script, I get strings of file paths that may contain environment variables, e.g. $FONTS/test.ttf or $TMP/file.txt .

Now I want to open these files as follows:

 open my $handle, "<$filename" or die $!; 

How can I now expand environment variables to an open call, for example, would a bash shell do?

+6
perl
source share
4 answers

If environment variables are set, you can use a simple replacement:

 $filename =~ s/\$(\w+)/$ENV{$1}/g; 
+12
source share

Why not just do it:

 $filename =~ s/\$\{(\w+)\}/$ENV{$1}/g; $filename =~ s/\$(\w+)/$ENV{$1}/g; 
+2
source share

Well the following is much more verbose, but it seems to handle the $FOO and ${FOO} syntax correctly.

 #!/usr/bin/env perl use warnings; use strict; my $filename = $ARGV[0]; print(" GIVEN: <$filename>\n"); my $expanded = ''; my @parts = split(/(\$\w+)|(\${\w+})/, $filename); foreach my $seg (@parts) { next if (not defined($seg)); $seg = ($ENV{$1} || '') if ($seg =~ m/\${?(\w+)}?/); $expanded .= $seg; } print("IS NOW: <$expanded>\n"); print(`echo " ECHO: <$filename>"`); # How the shell did it. 

Here is an example run ...

 $ ./expand '$TERM ---${TERM}--- ===${FOO}=== $FOO' GIVEN: <$TERM ---${TERM}--- ===${FOO}=== $FOO> IS NOW: <xterm-color ---xterm-color--- ====== > ECHO: <xterm-color ---xterm-color--- ====== > $ 

In this version, undefined characters are replaced by an empty string, like a shell. But in my applications, I would prefer to leave an unused invalid character in place, which makes it easier to see what went wrong. In addition, if you ruin the match between the brackets, the shell will give you a "bad replacement" error, but here we just return the line with the broken character still in place.

0
source share

Sorry, but you are mistaken.

for working in perl with SHELL variables, the correct syntax is: $ ENV {variable}

with GCC color output function:

 n=$(tput setaf 0) r=$(tput setaf 1) g=$(tput setaf 2) y=$(tput setaf 3) b=$(tput setaf 4) m=$(tput setaf 5) c=$(tput setaf 6) w=$(tput setaf 7) N=$(tput setaf 8) R=$(tput setaf 9) G=$(tput setaf 10) Y=$(tput setaf 11) B=$(tput setaf 12) M=$(tput setaf 13) C=$(tput setaf 14) W=$(tput setaf 15) END=$(tput sgr0) colorgcc() { perl -wln -M'Term::ANSIColor' -e ' m/not found$/ and print "$ENV{N}$`$ENV{END}", "$&", "$ENV{END}" or m/found$/ and print "$ENV{N}$`${g}", "$&", "$ENV{END}" or m/yes$/ and print "$ENV{N}$`${g}", "$&", "$ENV{END}" or m/no$/ and print "$ENV{N}$`$ENV{END}", "$&", "$ENV{END}" or m/undefined reference to/i and print "$ENV{r}", "$_", "$ENV{END}" or m/ Error |error:/i and print "$ENV{r}", "$_", "$ENV{END}" or m/ Warning |warning:/i and print "$ENV{y}", "$_", "$ENV{END}" or m/nsinstall / and print "$ENV{c}", "$_", "$ENV{END}" or m/Linking |\.a\b/ and print "$ENV{C}", "$_", "$ENV{END}" or m/Building|gcc|g\+\+|\bCC\b|\bcc\b/ and print "$ENV{N}", "$_", "$ENV{END}" or print; ' } 
0
source share

All Articles