0

Well

I have a 2D array matrix file like

0.5 0.8 0.9 0.10 
1.0 0.5 0.75 0.6
2.5 6.0 0.5 0.53
3.0 2.75 0.9 0.5

I want to read this file as csv and edit the file such as when the values are above (> 1) i want to edit it as 1.0  
so my matrix will look like

0.5 0.8 0.9 0.10 
1.0 0.5 0.75 0.6
1.0 1.0 0.5 0.53
1.0 1.0 0.9 0.5
3
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by 2teez
0
#!/usr/bin/perl
use strict; 
use warnings; 

my @matrix;

while (<DATA>){
    chomp;
    push @matrix, [split];
}

foreach my $row (@matrix){
    foreach my $cell (@$row){
        $cell = no_more_than_1($cell);
    }
}

foreach (@matrix){
    print join ' ', @$_, "\n";
}

sub no_more_than_1{
    my $nbr = shift;
    if ($nbr > 1){
        return '1.0';
    }
    else{
        return $nbr;
    }
}
__DATA__
0.5 0.8 0.9 0.10 
1.0 0.5 0.75 0.6
2.5 6.0 0.5 0.53
3.0 2.75 0.9 0.5
1

I felt like it's fun and that I can improve on the previous solution.

#!/usr/bin/perl
use warnings;
use strict;

while (<DATA>) {
print join "  ", map { $_ > 1.0 ? '1.0' : $_ } split / /, $_;
}

__DATA__
0.5 0.8 0.9 0.10
1.0 0.5 0.75 0.6
2.5 6.0 0.5 0.53
3.0 2.75 0.9 0.5

OUTPUT
0.5 0.8 0.9 0.10
1.0 0.5 0.75 0.6
1.0 1.0 0.5 0.53
1.0 1.0 0.9 0.5

Edited by 2teez

Votes + Comments
Nice and short.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.