[prog] Perl code

Jacinta Richardson jarich at perltraining.com.au
Sun Feb 6 11:44:18 EST 2005


The biggest reason this is failing is because of the space in your print 
string:
     print "$names [ $_ - 1 ]\n";
should be:
     print "$names[ $_ - 1 ]\n";

With this minor correction we now get:

Enter number:
1
2
3
^d
fred
betty
barney

If you wish to enter the numbers all together on the same line, ie:
    1 2 3
then we'll need to use split.

I've changed your code to use split, and also added some comments and 
minor improvements.

-----------------------------------------------
#!/usr/bin/perl -w
# Good to see you're using warnings!
# Let's now use strict as well, because it mades us
# write better code.
use strict;

my @names = qw# fred betty barney dino wilma
                 pebbles bamm-bam #;

print "Enter numbers separated by spaces on one line:\n";

# Get numbers from user:
my $numbers = <STDIN>;

my @numbers = split(/ +/, $numbers);

foreach (@numbers) {
      print "$names[$_ - 1] ";
}
print "\n";

-------------------------------------------------

This will now take: "1 2 3" or "1    2  3   "
and return "fred betty barney \n"

I hope this helps.

all the best,

     Jacinta Richardson

-- 
    ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
     `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
     (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
   _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
  (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |




More information about the Programming mailing list