in reply to question on Arrays
I'm getting a bit confused about what you're trying to do. First, there's nothing in your code that is looking for "^Z" to take an action on. Second, your code has two loops: an infinite while loop and a for loop. I'm guessing that your complaint about an infinite loop is about the for loop.
With the for loop, I see two problems. First, you are starting your iteration with element ID 1, which is actually the second element of the array. Arrays in Perl are zero based enumerated. Second, scalar(@arr) gives you the total of count of array elements. Instead, you probably should have used $#arr, which would provide you with the last array element ID. In other words, your for loop should have been:
for($x=1;$x<=$#arr;$x++)
Anyways, I think that the code below should either do what you're wanting or be close enough to give you a good starting point. It will repeatedly prompt a user for a number and either add it to the array if it doesn't exist in the array or exits out if a duplicate value was given.
use strict; my @arr; my $exit = 0; while ($exit == 0) { print "Enter a number: "; my $val = <>; chomp $val; if (grep $_ eq $val,@arr) { print "Value already exists.\n"; $exit++; } else { push @arr,($val); } } print "Array contains:\n"; foreach my $elem (@arr) {print "$elem\n";}
|
|---|