Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: A simple foreach question

by davidj (Priest)
on Mar 06, 2005 at 06:53 UTC ( #437005=note: print w/ replies, xml ) Need Help??

in reply to A simple foreach question

I believe the reason is this: You are receiving the input in list context. Therefore when you enter '2 3 4' it is being recieved as a string and the array has only one element. Now, when you iterate through your 1 element array, you are trying to use it as a number, but since the one element '2 3 4' is a string, only the 2 is being used. It would be better to do something like this:

#!/usr/bin/perl use strict; my @names = qw/ fred betty barney dino wilma peblles bamm-bamm /; chomp( my $list = <STDIN>); my @list = split(" ", $list); foreach (@list) { print " $names[ $_ - 1]\n"; } exit;

Comment on Re: A simple foreach question
Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://437005]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (15)
As of 2015-11-30 13:44 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (771 votes), past polls