Front page | perl.beginners |
Postings from December 2011
Re: multi-column array
Thread Previous
|
Thread Next
From:
Dermot
Date:
December 1, 2011 02:01
Subject:
Re: multi-column array
Message ID:
CAK+Utv+wC5V1xBax+wEEYTVihkhEzN9XWScBiFETM+EVecytew@mail.gmail.com
On 30 November 2011 23:06, Jeswin <phillyj101@gmail.com> wrote:
> I've been trying to figure out how to print 2 arrays into 2 columns. I
> came across this code and it works but gives me a problem in the
> output.
>
> *************************BEGIN CODE*********************************************
> sub transpose {
> map { my $i = $_; [ map $_->[ $i ], @_ ] } 0 .. $#{ $_[0] }
> }
> print "@$_\n" for transpose \( @unknown_abs, @unknown_conc );
>
> *************************END
> CODE************************************************
>
> *************************BEGIN OUTPUT******************************************
>
> 0.1
> 0.729843646443355
> 0.2
> 1.47255203636502
> 0.35
> 2.58661462124751
> 0.33
> 2.43807294326318
> 0.41 3.03223965520051
>
> *************************END OUTPUT*********************************************
>
> So 0.1, 0.2, 0.35, 0.33, 0.41 should be in one column and the other
> values next to it. I'm trying to figure out how to reduce precision
> with printf but not really sure about that.
Have a look perldoc -f sprintf (http://perldoc.perl.org/functions/sprintf.html)
I'm not too keen on that print statement but then I'm not massively
happy with my own version either because it fixes the number of
elements in the array.
use strict;
use warnings;
my @unknown_abs = ( 0.1, 0.2, 0.35, 0.33, 0.41);
my @unknown_conc = ( 0.729843646443355, 1.47255203636502,
2.58661462124751, 2.43807294326318, 3.03223965520051);
sub transpose {
return [ map { my $i = $_; [ map $_->[ $i ], @_ ] } 0 .. $#{ $_[0] } ];
}
my $arrayref = transpose ( \@unknown_abs, \@unknown_conc ) ;
for (@$arrayref) {
printf "%.4f %.4f\n", $_->[0], $_->[1];
}
The precision here is a floating point number with 4 places after
after the decimal point.
HTH,
Dp.
Thread Previous
|
Thread Next