Hi Perl Monks,
My interest is to find the mean from a LIST (10.12,14,16,18). The list is to uploaded from a text file (x.txt) with STDIN. So, I have written the following script i.e. mean.pl and the text file x.txt. But I am getting wrong results for number of elements (i.e.17) and mean (i.e. 0). The correct number of elements and mean should be 5 and 14, respectively. Can any perl monk help in this matter? I think my question might be a very silly one to the Perl Monks.
The perl script mean.pl goes like:
#!/usr/bin/perl use warnings; print"\n Enter the Filename (x.txt) with Data in List context: "; $filename = <STDIN>; chomp$filename; # open the file, or exit unless ( open(FILE, $filename) ) { print "Cannot open file \"$filename\"\n\n"; exit; } $list = <FILE>; print"\n List= $list\n"; @array=split('',$list); # To convert scalar to array print"\n Array From the List= @array\n"; $N_elements=@array; # To count number of elements in array print"\n Number of Elements= $N_elements\n"; # Sum of all elements in array: $sum=0; $sum=eval join '+',@array; # Mean of the list: $mean=$sum/$N_elements; # Line 21 print"\n Mean of the list= $mean\n"; exit;
Here goes the text file x.txt:
(10,12,14,16,18);The cmd has shown wrong results:
Enter the Filename (x.txt) with Data in List context: x.txt List= (10,12,14,16,18); Array From the List= ( 1 0 , 1 2 , 1 4 , 1 6 , 1 8 ) ; Number= 17 Use of uninitialized value $sum in division (/) at C:\Users\x\Desktop\ +mean.pl line 21, <FILE> line 1. Mean of the list= 0
The correct result should look like:
Enter the Filename (x.txt) with Data in List context: x.txt List= (10,12,14,16,18); Array From the List= ??? Number of Elements= 5 Mean of the list= 14
In reply to Why is the List upload with STDIN from a text file giving wrong result for mean? by supriyoch_2008
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |