in reply to Round numbers?

See sprintf  %g format specifier:
>perl -wMstrict -le "my @nra = ( 8.8458e-119, 1.06542e-52, 2.68e-36, 2.91405e-35, 0.0190644, 0.0205511, 0.004, ); for my $n (@nra) { my $fmt = $n > 0.001 ? '%5.2g' : '%5.3g'; printf qq{$fmt \n}, $n; } " 8.85e-119 1.07e-052 2.68e-036 2.91e-035 0.019 0.021 0.004
Update: This loop produces the same output without needing an intermediate variable:
printf qq{%5.*g \n}, $_ > 0.001 ? 2 : 3, $_ for @nra;

Replies are listed 'Best First'.
Re^2: Round numbers?
by Anonymous Monk on Oct 01, 2009 at 23:48 UTC
    Because I am new to Perl and don't understand it that much, can you please tell me how these lines interpret?
    for my $n (@nra) { my $fmt = $n > 0.001 ? '%5.2g' : '%5.3g'; printf qq{$fmt \n}, $n; }

    It's like:
    for my $n (@nra) { my $fmt=$n; if($n>0.001){ ????? } else { ?????? } printf qq{$fmt \n}, $n; }

    Thank you for your time!
      No, like:
      for my $n (@nra) { my $fmt; if ($n > 0.001){ $fmt = '%5.2g'; } else { $fmt = '%5.3g'; } printf qq{$fmt \n}, $n; }
      See Conditional Operator in perlop.

      Note that
          $x = $y > $z ? 'foo' : 'bar';
      is perhaps more clearly written as
          $x = ($y > $z) ? 'foo' : 'bar';

        A million thanx to you! It was very kind you explained all that to me!