How can I write in scientific notation using Perl formats?

I've always used printf, and I have never used write/ format. Is there a way to play printf("%12.5e", $num)using the format? I am having trouble processing perlform documentation , but I don’t see a direct way to do this.

EDIT: based on the answers I received, I will just continue to use printf.

+3
source share
2 answers

Short answer, do not use formats.

Unexplored answer, of course, just use sprintf:

#!/usr/bin/perl

use strict;
use warnings;

our $num = .005;

write;

format STDOUT =
@>>>>>>>>>>>>>>>>>
sprintf("%12.5e", $num)
.
Seriously, if you need something like Perl 5 formats, take a look Perl6::Form(note that this is a Perl 5 module, it just implements the proposed version of Perl 6 formats).
+2
source

I completely agree with the Hour. Owens in formats in general. Formatwas really spotted 15 years ago, but Formatfailed to cope with the rest of Perl.

, . formline, , Format. Format - . , . , , Format, .

A () :

use strict; use warnings;

sub print_line {
    my $pic=shift;
    my @args=@_;

    formline($pic,@args);
    print "$^A\n";
    $^A='';
}

my ($wlabel, $wlow, $whigh, $wavg)=(0,0,0,0);
my ($plabel,$plow,$phigh, $pavg);
my ($s_low,$s_high,$s_avg)=qw(%.2f %.2e %.2f);


my @results=( ["Label 1", 3.445, 0.00006678, .025],
           ["Label 2", 12.5555556, 55.112, 1.11],
           ["Wide Label 3", 1231.11, 1555.0, 66.66] );

foreach (@results) { 
    my $tmp;
    $tmp=length($_->[0]);
    $wlabel=$tmp if $tmp>$wlabel; 

    $tmp=length(sprintf($s_low,$_->[3]));
    $wlow=$tmp if $tmp>$wlow;

    $tmp=length(sprintf($s_high,$_->[2]));
    $whigh=$tmp if $tmp>$whigh;

    $tmp=length(sprintf($s_avg,$_->[1]));
    $wavg=$tmp if $tmp>$wavg;
}

print "\n\n";
my @a1=("Label", "Rate - Operations / sec");
my @a2=("Text", "Average", "High", "Low");
my @a3=("----------", "-------", "----", "---");
my $l1fmt="@".'|' x $wlabel."   @".'|'x($whigh+$wavg+$wlow+6);

my $l2fmt="@".'|' x $wlabel."    @".'|' x $wavg."   @".'|' x $whigh . 
           "   @".'|' x $wlow;
print_line($l1fmt,@a1);
print_line($l2fmt,@a2);
print_line($l2fmt,@a3);

$plabel="@".'>' x $wlabel;
$phigh="@".'>' x $whigh;
$pavg="@".'>' x $wavg;
$plow="@".'<' x $wlow;


foreach (@results) {
    my $pic="$plabel   $pavg   $phigh   $plow";
    my $mark=$_->[0];
    my $avg=sprintf($s_avg,$_->[1]);
    my $high=sprintf($s_high,$_->[2]);
    my $low=sprintf($s_low,$_->[3]);
    print_line($pic,$mark,$avg,$high,$low);
}
print "\n\n";

:

    Label         Rate - Operations / sec
    Text         Average      High       Low
 ----------      -------      ----       ---
      Label 1       3.44    6.68e-05   0.03
      Label 2      12.56    5.51e+01   1.11
 Wide Label 3    1231.11    1.56e+03   66.66

, , sprintf. , , , . "" , . , $plow, , Format. , "Rate - Operations/sec" 3 .

" " , , . .. , , . sprintf, .

.

+2

Source: https://habr.com/ru/post/1764756/


All Articles