On Wed, Sep 23, 2009 at 19:16, Mike McClain <mike.j...@nethere.com> wrote: > On Tue, Sep 22, 2009 at 05:09:26AM -0400, Shawn H Corey wrote: >> Roman Makurin wrote: >> >Hi All! >> > >> >right now im doing it in following way: >> >$size = @{[func_that_return_list_value]}; >> > >> >is there any best way to do it ? >> > >> See `perldoc -f scalar` http://perldoc.perl.org/functions/scalar.html > > I read the perldoc on scaler and then tried every combination > I could think of: > > perl -le ' sub farr{ return qw( k l m ); } > $a = @{[farr]}; > $b = scalar farr; > $c = scalar (farr); > $d = scalar [farr]; > $e = scalar @{farr}; > $f = scalar @{[farr]}; > $g = () = farr; > print "\n\$a = $a, \$b = $b, \$c = $c, \$d = $d, \$e = $e, \$f = $f, \$g = > $g";' > > $a = 3, $b = m, $c = m, $d = ARRAY(0x814f8e4), $e = 0, $f = 3, $g = 3 > > Unless there is a syntax I've missed, only a, f & g give the desired answer. > To my thinking a is clearly preferable to f but the winner has to be g. > =()= is much more legible than @{[]}, less prone to mistyping. > > Thank you Paul Johnson for bringing this to my attention. > > The original question was what's 'best'. > Does anyone know of a case where one of these expressions would fail? snip
Both the a and g cases only work because the assignment provides scalar context. Failure to recognize this may cause you to write my %h = ( a => @{[farr]}, g => () = farr, ); which results in either an error (if farr returns an even number), or worse, a very odd hash: my %h = ( 'a' => 'k', 'l' => 'm', 'g' => undef ); The solution is to force scalar context with scalar: #!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub farr { return qw/k l m/ } my %h = ( a => scalar @{[farr]}, g => scalar(() = farr), ); print Dumper \%h; Of course, the best solution is to make farr context aware with the poorly named [wantarray][1]: #!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub farr { my @a = qw/k l m/; return wantarray ? @a : scalar @a; } my @list = farr; my $count = farr; print "[...@list] has $count items\n"; my %h = ( h => scalar farr, ); print Dumper \%h; [1] : http://perldoc.perl.org/functions/wantarray.html -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/