stevenswj has asked for the wisdom of the Perl Monks concerning the following question:

say in shell you define: NUMS=( "one", "two", "three" ) export $NUMS How to access these array elements in a Perl script? I can't seem to get this to work. Thanks

Replies are listed 'Best First'.
Re: Environment variable is an array
by happy.barney (Friar) on Oct 29, 2010 at 08:32 UTC
    env variable is a string (see man execve, for example). Best way how to achieve required functionality is to use separator:
    # shell export NUMS="one:two:three" # perl my @nums = split /:/, $ENV{NUMS};
Re: Environment variable is an array
by ambrus (Abbot) on Oct 29, 2010 at 08:47 UTC

    Like Anon says above, shell arrays are a concept internal to the shell, they can't be exported.

    Here are some things you could do if you still want to pass an array of string. The easiest way might be to pass the values of the array as command-line arguments and access them as @ARGV.

    perl -we 'print "<<<$_>>>\n" for @ARGV;' -- "${NUMS[@]}"
    You could also write the values to a file (either a regular file or pipe) separated by nuls, and read that file from perl, eg.
    printf "%s\0" "${NUMS[@]}" | perl -we 'my @NUMS; { local $/ = "\0"; ch +omp(@NUMS = <STDIN>); }; warn "<<<$_>>>\n" for @NUMS; '

    You needn't use the standard input, you can pass the name or filedescriptor of the file to the script in the command line or environment.

    You could also avoid files and stuff the values in separate environment variables, but that gets ugly, so I recommend files instead.

    for k in "${!NUMS[@]}"; do export NUMS_$k=${NUMS[k]}; done; perl -we 'my @NUMS; while (my($k, $v) = each %ENV) { $k =~ /\ANUMS_(.+ +)\z/ and $NUMS[$1] = $v; } print "<<<$_>>>\n" for @NUMS;'
Re: Environment variable is an array
by cdarke (Prior) on Oct 29, 2010 at 09:59 UTC
    Just to add what others have said, on most shells (you don't say which shell, or version) if you export an array you only get the first element. I know that the Bash project was working on a method to do it, but I don't know if it was complete. You might ask on an AT&T mailing list here about the Korn shell.

    Those shells which allow exporting of functions (export -f function_name) give interesting results, and it might be possible to embed the array in a function and export that - but you will have to unpack it in Perl and the format varies between shell versions.
      Thanks for help, I'll just export a comma-separated string instead of a shell array then parse it.
Re: Environment variable is an array
by Anonymous Monk on Oct 29, 2010 at 08:30 UTC
    Enviroment variables are key/value pairs, they are not arrays. See %ENV in perlvar
    perl -MData::Dumper -le " print Dumper( \%ENV ) "