tags:

views:

57

answers:

2

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

I now want to open those files like this:

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

How can I now expand the environment variables prior to the open call, as e.g. the bash shell would do?

A: 

You can make use of backticks as:

$filename = `echo \$FONTS/test.ttf`; # $filename will now be /dir/to/fonts/test.ttf
open( FILE1, "<$filename" ) or die;
codaddict
Wouldn't this be a security risk if my string contained "$FONTS/test.ttf; rm -rf /" ?
Fabian
+5  A: 

If the environmental variables are set, you can use a simple substitution:

$filename =~ s/\$(\w+)/$ENV{$1}/g;
eugene y
Neat and succinct - and, as ever, error processing will screw it up. Specifically, if one of the environment variables referenced is not set, you will at best get an unexpected path; you may also get warnings about accessing undefined variables from Perl. Although there are other shell notations (like `${TMP}`), they are seldom used in contexts where that will be a problem.
Jonathan Leffler
@Jonathan, the standard behavior for bash is to substitute the empty string for a missing variable, so this code does handle that error condition in the way the OP asked. I agree on the alternate shell notations I use `${FOO:?}` quite a lot in scripts to force bash to throw errors on unset variables.
Ven'Tatsu