LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Sorting through associative array with user input (https://www.linuxquestions.org/questions/linux-newbie-8/sorting-through-associative-array-with-user-input-717297/)

nobody123 04-06-2009 08:14 PM

Sorting through associative array with user input
 
Hi there. Thanks for taking the time to read this question. It's probably something I'm missing on my part. Anyways, onto the question.

I'm working on an address book and storing the records via hashes. I want the users to be able to search for an address by using the contact number. Here's the code I came up with:

Code:

print "\nEnter the number you wish to search for";
$phoneSearch=<STDIN>;
chomp ($phoneSearch);
@LIST = grep($phoneSearch ,%addresses); #searches for records that have
                                        #the specified number and
                                        #assigns it to @LIST
                                       
if (@LIST != null) #checks if results are found
{
print "@LIST";
$#LIST = -1; #empties out array for reuse
}
else
{
print "No records found...";
}

The problem with this code? The array doesn't empty itself after it prints the array. So even though the user specifies a phone number not in the records, it will output the array regardless. Any help will be greatly appreciated.

grunt547 04-06-2009 08:26 PM

To empty a Perl array:
Code:

@LIST = ();
Also your use of the bareword 'null' looks weird. To check if the list holds anything, you can just say:
Code:

if (@LIST) { ... }
Try adding "use strict;" to the beginning to catch things like that.

nobody123 04-06-2009 10:39 PM

Quote:

Originally Posted by grunt547 (Post 3500636)
To empty a Perl array:
Code:

@LIST = ();
Also your use of the bareword 'null' looks weird. To check if the list holds anything, you can just say:
Code:

if (@LIST) { ... }
Try adding "use strict;" to the beginning to catch things like that.

Okay, after a ton of errors (mostly due to the fact that I hadn't declared anything) It still does not function correctly. I implemented your code but it just doesn't empty it (the LIST array). Thanks for the help though :)

nobody123 04-08-2009 01:55 PM

Update
 
Yeah, it works now. I modified my code a bit. There were a few errors (e.g. not greping properly). I'll post my code up for anyone who is interested...


Code:

print "\nEnter the number you wish to search for: ";
my $phoneSearch=<STDIN>;
chomp ($phoneSearch);
my @LIST = grep(/$phoneSearch/, %addresses);


if (@LIST)
{
  print "@LIST";
  print "\nPerform another search?(Y/N): ";
  $menuExit=<STDIN>;
  chomp ($menuExit);
  @LIST = ();
}
else
{
 print "\nNo records found...\n";
 print "\nPerform another search?(Y/N): ";
 $menuExit=<STDIN>;
 chomp ($menuExit);
}



All times are GMT -5. The time now is 06:15 PM.