in reply to rel2abs of a path with env

You're kind of getting off into the weeds now and there's probably not going to be an off the shelf module to do what you're wanting. The (naïve, obvious) solution would be to round trip things through a shell, but that's going to have security implications.

use feature qw( say ); use IPC::Run qw( run ); my $path = q{/a/b/c/$USER}; my $output = q{}; run( ['/bin/bash', '-c', qq{echo -n "$path"}, ], q{>}, \$output ); say qq{Output: $output};

The safer alternative is going to be walking over your strings and using something like s{\$(?: \{? (\S+) \}? )}{$ENV{$1} // qq{UNDEF:$1}}xge; to expand things yourself.

Edit: Obviously that's an imprecise regexp and to be more bulletproof you'd want to use Regexp::Common and be fancier pulling any curly wrapped bit(s) out with something like qr/\$ ($RE{balanced}{-parens=>q{{}}}) / and then working with that instead.

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: rel2abs of a path with env
by ovedpo15 (Pilgrim) on Jun 07, 2021 at 14:28 UTC
    Thanks. I wrote the following regex:
    sub resolve_env_in_path { my ($path) = @_; $path =~ s/\$\{(\w+)\}/$ENV{$1}/g; $path =~ s/\$(\w+)/$ENV{$1}/g; return $path; }
    What do you think?

      One thing your version silently strips out any undefined variables; using the /e modifier lets you have an expression rather than just a quoted string so you can do a bit of logic on the RHS of the substitution ...{ $ENV{$1} // qq{MISSING:$1} }e (so you get an indication what's missing).

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.