Reputation: 847
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 ?
Upvotes: 0
Views: 114
Reputation: 91518
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.
Upvotes: 7