TTaJTa4
TTaJTa4

Reputation: 840

Perl script does not recognize paths which contains environment variables

I got a file with a path on each line. I insert those lines into an array @dirs. Some of the paths include environment variables. An example of a valid file with paths:

/some/valid/path
$HOME/dir
$SOME_ENV/dir

Each path, I would like to check if it contains a file called abc. So I use:

foreach my $dir (@dirs) {
   chmod($dir);
   my $file = $dir."/"."abc";
   print "invalid dir: $dir" unless((-e $file) && (-s $file));
}

But, for some reason, it does not recognize the environment variables, meaning it fails even though $SOME_ENV/dir contains the abc file.

Also, the script does recognize those environment variables, if I use it as following:

print $ENV{SOME_ENV}."\n";
print $ENV{HOME}."\n";

Furthermore, I tried to use the abs_path of the Cwd module, in order to get the real path of the path (so it won't include the environment variable), but it also, does not recognize the environment variable.

why (-e $file) does not recognize the environment variable? How can I solve this issue?

Upvotes: 0

Views: 608

Answers (1)

Chris Turner
Chris Turner

Reputation: 8142

There is nothing in your code evaluating $dir for environment variables inside of it, so you'd need to add that. A very simplistic way could be done like this - using a regular expression to find the variables and then replacing them with their values in the %ENV hash.

$dir =~ s/\$([A-Z0-9_]*)/$ENV{$1}/g;

Upvotes: 6

Related Questions