Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

I just recently started to taking a course in Perl. In one of my exercises I have to write a script that prints out a sorted list of environment variables. Well for some reason it is only printing out 3 of the 5 that I specified. It prints out HOME, HOSTNAME and USER, but leaves out TERM and SHELL. Could someone tell me what I'm doing wrong in my code.

#!/usr/bin/perl

%env = ('USER',
'SHELL',
'HOSTNAME',
'TERM',
'HOME');

foreach $key (sort(keys(%env))){
print "$env $ENV{$key}\n";
}

Thoughts?

just wanted to add in case this is confusing. i'm trying to get a printout of the actual user, shell, term and home from ENV settings.

so in this case it would be...

/home/lokeey
perlhowto.com
/bin/bash
xterm
lokeey

...but instead it's only printing...

xterm
lokeey

Here is my final script.

#!/usr/bin/perl

@key = qw(SHELL USER LANG HOSTNAME TERM HOME);

foreach my $key (sort(keys %ENV)){
foreach $check (@key){
if ($key eq $check){
print "$key: $ENV{$key}\n";
}
}
}


Solution

#!/usr/bin/perl

@key = qw(SHELL USER LANG HOSTNAME TERM HOME);

foreach $key (@key){
print "$key: $ENV{$key}\n";
}

The problem is that you

The problem is that you defined a hash (%env) and you assigned a list of values to that hash;, when you assign a list to a hash the first list item is considered a key, the second item is the value of the previous list item, the third item is another key and so on.

If you use an array (instead of a hash) and make a slight change in the 'foreach' sentence then your code should work.

Regards,
Toshiro.