[prog] Perl code

Dominik Schramm dominik.schramm at slivery.cotse.net
Sun Feb 6 00:35:23 EST 2005


Hi,

Noir <acknak_halflife at yahoo.co.uk> writes:

> Can anyone tell me what's wrong with the following
> code?

Two things, in my opinion:
the input record separator has to be changed, and the interpretation
inside the quoted output string fails.

> #!/usr/bin/perl -w
> @names = qw#fred betty barney dino wilma pebbles
> bamm-bamm#;
> print "Enter number:  \n";
> chomp (@number = <STDIN>);
> foreach (@number) {
>     print "$names [ $_ - 1 ]\n";
> }

wanted behavior:

> Input: 1 2 3
> Output (after ctrl-d): fred betty barney

Here's the commented code:

> #!/usr/bin/perl -w
> @names = qw#fred betty barney dino wilma pebbles
> bamm-bamm#;
> print "Enter number:  \n";
> chomp (@number = <STDIN>);

The array @number has only one (!) element, "1 2 3". Perl splits your
input according to the predefined variable $/ (or
alternatively $INPUT_RECORD_SEPARATOR with "use English"), whose
default value is "\n". If you want the input to be split into
space-separated values (i.e. one space!), put 
  $/ = " "

before the (implicit) split:
  $/ = " ";
  chomp (@number = <STDIN>);

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

Perl tries hard to do this right, but fails here. I don't know the
rules used by Perl to decide what kind of interpretation/interpolation
to use inside quotes, but you make it very hard for Perl to realize
that you want an array element from @names, whose index should be the
result of a subtraction. 
Personally I prefer to put such complicated expressions 
outside the "": 
  print $names[$_-1], "\n";

However, I just tried the following and it also works:
  print "$names[ $_ - 1 ]\n";

This *does not* work: print "$names [ $_ - 1 ]\n" -- the only
difference is the space before the opening bracket.

Note that the input values really have to be separated by single
spaces. If you put two spaces between the two numbers, e.g. "1  2",
Perl sees three values:
1 "" 2
The empty space interpreted numerically is 0; $names[0-1] is
$names[-1], and that is the last array element.

So here is some code that works as expected:

#!/usr/bin/perl -w
@names = qw#fred betty barney dino wilma pebbles
bamm-bamm#;
print "Enter number:  \n";
$/=" ";
chomp(@number = <STDIN>);
foreach (@number)
{
    print $names[ $_ - 1 ], " ";
}

I replaced "\n" in the output string by " " to match the output format
to the input format.

hope this helps,
dominik



More information about the Programming mailing list