in reply to .env loading the dot env file?

See Get default login environment and the discussion therein. There is Shell::EnvImporter.

I'm not sure if you really want the effects of a shell script, or just something that "looks like sh environment commands". If so, your approach seems good, but doesn't respect quoted constructs.

In your code, I would at least change the split() to a more robust parser, so that it also understands foo=bar=baz as setting foo to bar=baz:

#my ($key, $value) = split /\s*=\s*/, $line; if( $line =~ /^\s*([^=]+)=(.*?)\s*$/ ) { my ($key,$value) = ($1,$2); $ENV{$key} = $value; } else { croak "Malformed environment line: '$line'"; };

Support for foo="bar=baz" and foo=\"bar=baz\" would also be addable, but if you want to support multiline values, you'll have to switch away from line-based parsing.

Updated: The capturing parentheses were missing for the key, spotted by Anomalous Monk

Replies are listed 'Best First'.
Re^2: .env loading the dot env file?
by szabgab (Priest) on Mar 28, 2021 at 09:24 UTC
    I think in the cases I saw this, the .env file was more like an INI file without any sections and certainly without any shell-like executions. Just plain key-value pairs. I am not sure even quotes are needed. However splitting to only 2 values should be used so the value part could contain an equal sign as well. Better yet, use your suggestion.

    I am still wondering how much is this a "standard practice" or a good practice?

      It is definitely not "best practice" to parse config files of any format that is not your own in an ad hoc way. It's a last resource if you can't figure out the format or proper way to use it for affecting your environment externally to your Perl program; that said, if you have to do it you have to do it. Try not to, though.