Dav1
Dav1

Reputation: 31

How can I write a Perl script that reads from another file?

I want to write a Perl Script that reads a file.txt with columns of numbers,

20  30  12
31  20  54
63  30  21
11  12  10

and do some calculations, for example the mean. I don't know how to declare and initialize it. I've got this example, in which is looking for the median, and it has the data declared, in my case, the data is in a file, not in the script and want to calculate the median. there is it.. #!/usr/bin/perl

#data points 
@vals = ( 33, 23, 55, 39, 41, 46, 38, 52, 34, 29, 27, 51, 33, 28 ); 
print "UNSORTED: @vals\n"; 

#sort data points 
@vals = sort(@vals); 
print "SORTED: @vals\n"; #test to see if there are an even number of data points 
if( @vals % 2 == 0) { 

#if even then: 
$sum = $vals[(@vals/2)-1] + $vals[(@vals/2)]; 
$med = $sum/2; 
print "The median value is $med\n";
}
else{ 
#if odd then: 
print "The median value is $vals[@vals/2]\n";
} 
exit;

Upvotes: 0

Views: 551

Answers (3)

stevenl
stevenl

Reputation: 6798

Here are suggested functions to use (see the function reference):

  1. Open your file for reading: use the open function
  2. Loop through each line: while (my $line = <$filehandle>)
  3. Remove the trailing newline: use chomp
  4. Extract the values from each line: use the split function
  5. Store the values in an array: use push

To verify that your array has what you want at the end:

use Data::Dumper;
print Dumper \@vals;

UPDATE

Without giving you the entire answer (since this is homework) have a look at the sample code in each entry of the function reference.

Here's something to get you started:

open my $filehandle, '<', $filename
    or die "Couldn't open $filename";
while (my $line = <$filehandle>) {
    # do stuff with $line
}
close $filehandle;

Upvotes: 1

phatfingers
phatfingers

Reputation: 10250

Use the open command. Plenty of good examples on that page.

Upvotes: 2

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185219

This shell one-liner multiply first col with second one :

perl -lane 'print $F[0] * $F[1]' <FILE>

EDIT: And the perl script version with your new requirements and the file with 3 cols :

#!/usr/bin/perl

use strict;
use warnings;

my (@vals, $sum, $med);

while (<>) {
    @vals = split;

    print "UNSORTED: @vals\n"; 

    #sort data points 
    @vals = sort(@vals); 
    print "SORTED: @vals\n"; #test to see if there are an even number of data points 

    if(@vals % 2 == 0) { 
        #if even then: 
        $sum = $vals[(@vals/2)-1] + $vals[(@vals/2)]; 
        $med = $sum/2; 
        print "The median value is $med\n";
    }
    else{ 
        #if odd then: 
        print "The median value is $vals[@vals/2]\n";
    } 

    print "\n";
}

You may understand what's going on instead of just cut & paste ;)

To run the script :

./script.pl file_with_cols.txt

Upvotes: 1

Related Questions