Win has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I'm having difficulty working out how to return the variables a, b and R2 from the subroutines as three separate variables.
my $lfit = Statistics::LineFit->new(); $lfit->setData($x_ref, $y_ref); printf "a=%.4f, b=%.4f, R2=%.4f\n", $lfit->coefficients(), $lfit->r +Squared(); return "a=%.4f, b=%.4f, R2=%.4f\n", $lfit->coefficients(), $lfit-> +rSquared(); }

Replies are listed 'Best First'.
Re: Returning Statistics::LineFit variables from a sub
by grinder (Bishop) on Nov 22, 2007 at 17:33 UTC

    Your code, as posted, works just fine for me. If you want, you could list assign the results from the coefficients method. Might make things a bit more self-documenting:

    use strict; use warnings; use Statistics::LineFit; my $fit = Statistics::LineFit->new; $fit->setData( [qw[ 1 2 3 4 5 6 7]], [qw[ 2 3 4 5.5 6.5 7.5 8.5]], ) or die; my ($intercept, $slope) = $fit->coefficients; printf "i=%.4f, s=%.4f, R2=%.4f\n", $intercept, $slope, $fit->rSquare +d; # or return ($fit->coefficients, $fit->rSquared);

    Maybe you're calling your function that does this stuff in scalar context, and thus flattening the return list? What exactly are you getting back?

    • another intruder with the mooring in the heart of the Perl

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Returning Statistics::LineFit variables from a sub
by andreas1234567 (Vicar) on Nov 22, 2007 at 17:44 UTC
    I would use a hash reference. See perldata and perlref. Are you still struggling with LineFit.pm error due to undef value?
    use strict; use warnings; use Statistics::LineFit; use Data::Dumper; sub get_hashref { my ($x_ref, $y_ref) = ([1,2,3], [4,5,6]); my $lfit = Statistics::LineFit->new(); $lfit->setData($x_ref, $y_ref); my ($intercept, $slope) = $lfit->coefficients(); my $rSquared = $lfit->rSquared(); my $hashref = { a => $intercept, b => $slope, c => $rSquared }; return $hashref; } # ------ main ------ my $hr = get_hashref(); print Dumper($hr); __END__ $ perl -l 652420.pl $VAR1 = { 'c' => '1', 'a' => '3', 'b' => 1 };
    --
    Andreas