0

Hello I have a matrix which contains floats and int numbers I want to print it to a file in a way if it's not integer print the value rounded to 1 number after float. Below is my code

use Scalar::Util::Numeric qw(isint);

    for ( $i = 0 ; $i < $#matrix ; $i++ ) {
    for ( $j = 0 ; $j < $#{ $matrix[0] } ; $j++ ) {
        if (not isint $matrix[$i][$j] ) {

            printf MYFILE ("%.1f",$matrix[$i][$j]{score});
        }
        else {
            print MYFILE $matrix[$i][$j]{score}.' ';
        }
    }
    print MYFILE "\n";
}

The problem is that this code output write everything as float even if it is an integer. How to fix it ?

Mariya
  • 847
  • 1
  • 9
  • 25
  • 2
    What is the content of @matrix? – Toto Sep 11 '13 at 12:46
  • It outputs in a floating point format because you tell it to in your `printf` statement. `%f` is the format specifier for single precision floating point numbers. – Hunter McMillen Sep 11 '13 at 12:47
  • 1
    The condition `$i < $#matrix` will stop one short of the end of your array. You need `$i < @matrix` or `$i <= $#matrix`. `$#matrix` is the number of the last element. Also, a more Perlish way to write this (and simpler) is `for my $i (0 .. $#matrix)`. – TLP Sep 11 '13 at 12:47
  • first row is 0 and the rest floats, ints and 0 – Mariya Sep 11 '13 at 12:47
  • 4
    I guess ` $matrix[$i][$j]` is a reference to a hash because of `$matrix[$i][$j]{score}` used in print statement. So it 's never an int. – Toto Sep 11 '13 at 12:49
  • `$#{ $matrix[$i] }` <== – mpapec Sep 11 '13 at 12:49
  • @M42 That's your problem right there. – TLP Sep 11 '13 at 12:51
  • Thanks all and @M42 yes it is the right answer – Mariya Sep 11 '13 at 12:59

1 Answers1

7

Here is my comment --> answer:

I guess $matrix[$i][$j] is a reference to a hash because of $matrix[$i][$j]{score} used in print statement. So it 's never an int.

I'd do (with some fixes):

for ( my $i = 0 ; $i < $#matrix ; $i++ ) {
#   __^^
    for ( my $j = 0 ; $j < $#{ $matrix[$i] } ; $j++ ) {
    #                                __^^
        if (not isint $matrix[$i][$j]{score} ) {
        #                          __^^^^^^^
            printf MYFILE ("%.1f",$matrix[$i][$j]{score});
        }
        else {
            print MYFILE $matrix[$i][$j]{score}.' ';
        }
    }
    print MYFILE "\n";
}

And don't forget:

use strict;
use warnings;

in all your scripts, always.

Toto
  • 89,455
  • 62
  • 89
  • 125