[prog] Perl code

Noir acknak_halflife at yahoo.co.uk
Mon Feb 7 20:46:06 EST 2005


Thanks for the help. I didn't know that Perl is so
fussy about spacing. I don't like to use "use strict"
unless the code is more than one window long for
everytime I have to use "my".

--- Jacinta Richardson <jarich at perltraining.com.au>
wrote:

> 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


		
__________________________________ 
Do you Yahoo!? 
Yahoo! Mail - Easier than ever with enhanced search. Learn more.
http://info.mail.yahoo.com/mail_250


More information about the Programming mailing list