Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2002
    Thanked 0 Times in 0 Posts

    querying numbers in text file

    Many thanks in advance for your help! First, I'll show you what I'm trying to do and then the code I'm using.

    I'd like to query a text file with the following numbers organized as such:
    10 35
    20 75
    45 50
    50 98
    36 45

    Ave. column 1: 32.2
    Ave. column 2: 60.6

    So what I'm trying to do first is to query the lines individually and just print the output to see if it's working.

    #!/usr/bin/perl -w

    use strict;

    open DATA, 'data.txt' or die "Can't open data.txt: $!\n";

    my @data;

    # get the data
    while ( <DATA> ) {
    my @d = /(\d+)/g;

    push @{$data[$_]}, $d[$_] for 0 .. $#d;

    for ( @data ) {
    # assign line number [x] to a variable
    my $line = @$_[0];

    # trying to separate the numbers on the line
    my @numbers = split (/ /, $line);

    # just print the first line's first number
    my $test_var = $numbers[0];
    print "$test_var\n";

    The Output:

    Printed both numbers on separate lines. I can't figure out what I'm doing wrong but it must have something to do with my use of 'split'. Good karma points for anyone that helps! TIA!

  2. #2
    Regular Coder
    Join Date
    Jul 2002
    London, UK
    Thanked 0 Times in 0 Posts
    Hehe, I think lines like this:
    push @{$data[$_]}, $d[$_] for 0 .. $#d;

    Scare people a bit when they're thinking of replying.

    Why not try something simpler, like:
    #!/usr/bin/perl -w 
    use strict; 
    open (DATA, "data.txt") or die "Can't open data.txt: $!\n"; 
    my @col1, @col2, $temp1, $temp2; 
    # get the data 
    while ( <DATA> ) { 
    ($temp1, $temp2) = split;
    push (@col1, $temp1);
    push (@col2, $temp2);
    printf ("Average of first column is %.2d\n", average(\@col1));
    printf ("Average of second column is %.2d\n", average(\@col2));
    sub average {
    my $array = shift;
    my $sum;
    foreach (@{$array}) {
    $sum += $_;
    return ($sum / ($#{$array} + 1));
    Don't know if that'll work or not, I'm fairly sure it will but I haven't been able to test it yet.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts