[Kc] Perl Noob

Andrew Moore amoore at mooresystems.com
Wed Sep 19 08:24:36 PDT 2007

On Wed, Sep 19, 2007 at 10:06:18AM -0500, Emmanuel Mejias wrote:
> In this exercise the instructor was asking that I use the pre-defined
> environment variable hash that is discussed in this lesson, which is print
> %ENV; so that is why I created the script as a hash originally. I'm just
> confused as to why it only prints out 3 and skips every other one.

%ENV is already defined to contain a hash of things like:

         'PWD' => '/home/amoore',
         'LANG' => 'en_US',
         'USER' => 'amoore',

It's pretty much always defined when perl is running, so you don't
have to define it yourself or anything.

And so you can certainly print stuff out of it as it sounds like your
instructor asked you to.

print "HOME is: $ENV{'HOME'}\n";

Or, you could walk through a list of terms to print out:

foreach my $key qw( HOME USER TERM ) {
    print "$key is set to: $ENV{$key}\n";

You can even define that list of keys in advance:

my @keys = qw( HOME USER TERM );
foreach my $key ( @keys ) {
    print "$key is set to: $ENV{$key}\n";

Or, you could walk through each of the keys in the hash and print out
the values in order to get them all (especially if you didn't know
what keys may be in there when you wrote the program):

foreach my $key ( keys %ENV ) {
    print "$key is set to: $ENV{$key}\n";

It appears that you were trying to create a list of keys, like: my
@keys = qw( HOME USER TERM ); but using a hash. That's probably not a
good use of a hash, as you're discovering.

Hope this helps a bit, please ask more and show us your code if not.


More information about the kc mailing list