Connecting Tech Pros Worldwide Forums | Help | Site Map

Perl read in file and sort values

Newbie
 
Join Date: Nov 2005
Posts: 3
#1: Nov 18 '05
Perl Experts:
open(INFILE, $filename) or die("Cannot read input file: $!");

#How can I use this while loop to scan/read numbers from three lines and #find the smallest number ?

while ( <INFILE> ) {

@words = split();

last;
}

KUB365's Avatar
Administrator
 
Join Date: Jul 2005
Location: Portland, OR
Posts: 975
#2: Nov 18 '05

re: Perl read in file and sort values


Well you have the read in of the file part right.

The @words=split(); part doesn't need to be there. That with the "Perl Experts:" pretty much gives away that you just copied the code and pasted it here, with no attempt to work on it.

I will help you out though. Here is a simple algorithm with some links to help you along.
  1. Read file into an array
  2. Sort the data in the array - more
  3. Print specific array element. Output the first item in the array if your sorted from smallest to largest or out put the last item in an array if you sorted from largest to smallest.
All the information you need to do this problem is there. The algorithm and the links to the proper information. Put the pieces together and see if it works.

If you run into any problems, post your code here and we will help you out.
Newbie
 
Join Date: Nov 2005
Posts: 3
#3: Nov 19 '05

re: Perl read in file and sort values


Ok I have the following Perl code now... it doesnt print me out $min.. can anyone tell me why ?

Expand|Select|Wrap|Line Numbers
  1.  #! /usr/bin/perl 
  2.  
  3. #open file
  4. open(FILE,"gadzooks") or die("Unable to open file");
  5.  
  6. #read file into an array
  7.  
  8. @data = <FILE>;
  9.  
  10. $min = 10000;
  11. $max=0;
  12.  
  13.  
  14. while (<FILE>) {
  15. @data = <FILE>;
  16. @words = split( );
  17. foreach$n(@data){
  18. if($n<$min){
  19. $min = $n;
  20. print $min;
  21. }
  22. last;
  23. }
  24. }
  25.  
  26. #close file
  27. close(FILE);
  28.  

Quote:

Originally Posted by KUB365

Well you have the read in of the file part right.

The @words=split(); part doesn't need to be there. That with the "Perl Experts:" pretty much gives away that you just copied the code and pasted it here, with no attempt to work on it.

I will help you out though. Here is a simple algorithm with some links to help you along.

  1. Read file into an array
  2. Sort the data in the array - more
  3. Print specific array element. Output the first item in the array if your sorted from smallest to largest or out put the last item in an array if you sorted from largest to smallest.
All the information you need to do this problem is there. The algorithm and the links to the proper information. Put the pieces together and see if it works.

If you run into any problems, post your code here and we will help you out.

Reply