[Kc] Perl Noob

Frank Wiles frank at wiles.org
Tue Sep 18 12:01:47 PDT 2007

On Tue, 18 Sep 2007 13:48:02 -0500
"Emmanuel Mejias" <emmanuel.mejias at gmail.com> wrote:

> Cool! Thanks all for the feeback and links. I've hit a few of those
> in the past as well. I'm like John as well, I need to do it to learn
> it. I've been in the BASH world so a lot of this stuff is new to me
> and I'm trying to relate how some of the things you can do in Bash
> how they work in Perl.
> Well here goes. I just recently started taking an online course in
> Perl and I've also been using Perl by Example book as a reference. 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 doesn't matter what
> order I put the environment variables in, it just prints out every
> other one. In this case it prints out HOME, HOSTNAME and USER, but
> leaves out TERM and SHELL. What am I not doing right in my code?
> #!/usr/bin/perl
> %env = ('USER',
> 'SHELL',
> 'TERM',
> 'HOME');
> foreach $key (sort(keys(%env))){
> print "$env $ENV{$key}\n";
> }
> Thoughts?

  You're using a hash like an array when you shouldn't be: 

  What that is doing is creating this: 

  $env{USER} = 'SHELL';
  $env{HOSTNAME} = 'TERM'; 
  $env{HOME} = ''; 

  Do this instead: 

  my @envs = qw( USER SHELL HOSTNAME TERM HOME ); 

  foreach my $env ( @envs ) { 
     print "$env $ENV{$env}\n"; 

   Frank Wiles, Revolution Systems, LLC. 
     Personal : frank at wiles.org  http://www.wiles.org
     Work     : frank at revsys.com http://www.revsys.com 

More information about the kc mailing list