[Kc] Perl Noob

Emmanuel Mejias emmanuel.mejias at gmail.com
Wed Sep 19 12:21:30 PDT 2007


On 9/19/07, Andrew Moore <amoore at mooresystems.com> wrote:
>
> 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.
>
> -Andy
>
> _______________________________________________
> kc mailing list
> kc at pm.org
> http://mail.pm.org/mailman/listinfo/kc
>

That worked great, Andrew! Thanks! I added my sort and two extra lines so it
does what it's suppose to do and  prints out envirnoment variables that I
was asking it to print. here is my end result:

#!/usr/bin/perl -w

@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";
              }
          }
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/kc/attachments/20070919/5aab21ec/attachment.html 


More information about the kc mailing list