perl YAML.pm dump array without quotes

Viewed 145

I am writing a Perl script to generate a docker-compose.yml file. I am using the YAML.pl module's DumpFile method to write a complex hash to a file in YAML format.

Some of the arrays are dumping correctly, that is to say, the elements are unquoted, e.g.,

"environment" => [
    'MYSQL_ROOT_PASSWORD=secret', 'MYSQL_DATABASE=db',
    'MYSQL_USER=dbadmin',         'MYSQL_PASSWORD=secret2',
],

becomes

 environment:
      - MYSQL_ROOT_PASSWORD=secret
      - MYSQL_DATABASE=db
      - MYSQL_USER=dbadmin
      - MYSQL_PASSWORD=secret2

However there are some arrays that contain what are supposed to be arguments with values comprised of environment variables that docker-compose will get from the environment, i.e., I CANNOT output the raw values here, I need to output the env var that docker-compose will use to get the value. These are being dumped quoted:

"args" => [
    'APP_CODE_PATH=${APP_CODE_PATH_CONTAINER}',
    'APP_GROUP=${APP_GROUP}',
    'APP_GROUP_ID=${APP_GROUP_ID}',
    'APP_USER=${APP_USER}',
    'APP_USER_ID=${APP_USER_ID}',
    'TARGET_PHP_VERSION=${PHP_VERSION}',
    'TZ=${TIMEZONE}'
],

becomes:

args:
      - 'APP_CODE_PATH=${APP_CODE_PATH_CONTAINER}'
      - 'APP_GROUP=${APP_GROUP}'
      - 'APP_GROUP_ID=${APP_GROUP_ID}'
      - 'APP_USER=${APP_USER}'
      - 'APP_USER_ID=${APP_USER_ID}'
      - 'TARGET_PHP_VERSION=${PHP_VERSION}'
      - 'TZ=${TIMEZONE}'

The output is not supposed to be quoted.

I've combed the YAML.pm docs, but I cannot find anything specific to this question there.

I suspect it is how I'm entering the values in the array, but I can't figure out what I'm doing wrong.

2 Answers

Use YAML::Syck instead. You can turn off that quoting, and it's off by default:

use v5.26;
use YAML::Syck;

my $hash = {
    "args" => [
        'APP_CODE_PATH=${APP_CODE_PATH_CONTAINER}',
        'APP_GROUP=${APP_GROUP}',
    ],
    };

print Dump($hash);

Now it's unquoted:

---
args:
  - APP_CODE_PATH=${APP_CODE_PATH_CONTAINER}
  - APP_GROUP=${APP_GROUP}

You could use YAML::PP instead. It tries to only quote things if really necessary, or it would look ambiguous.

YAML.pm is old, it was written for YAML 1.0, and it has a lot of bugs (as well as YAML::Syck). See matrix.yaml.io.

use YAML::PP qw(Dump);
print Dump($data);

Also, YAML::PP supports the official YAML 1.1 and 1.2 Schemas (regarding numbers, booleans etc.), while YAML.pm, YML::XS and YAML::Syck do not.

(Disclaimer: I'm the author of YAML::PP)

Regarding "The output is not supposed to be quoted": That should actually not matter. I don't think it would stop working just be cause the values are quoted. I couldn't imagine why that would be the case.

Related