develooper Front page | perl.perl5.porters | Postings from February 2001

Re: [ID 20010220.003] Totally unclear behaviour in the looking good code

Thread Previous | Thread Next
From:
Robin Barker
Date:
February 20, 2001 07:39
Subject:
Re: [ID 20010220.003] Totally unclear behaviour in the looking good code
Message ID:
200102201539.PAA28974@tempest.npl.co.uk
> Consider the following code:
> -------------------------------------------------------
> #!/usr/bin/perl -w
> 
> use strict;
> use diagnostics;
> 
> sub bad_func
>   {
>     my ($key) = @_;
>     my %hash = (
> 		'key1' => 'value1',
> 		'key2' => 'value2',
> 	       );
>     return unless $hash{$key};
>     return $hash{$key};
>   }
> 
> sub value1 { return bad_func('key1'); }
> sub value2 { return bad_func('key2'); }
> sub value3 { return bad_func('key3'); }
> sub value4 { my $r = bad_func('key4'); return $r; }
> 
> testfunc('key1',value1(),'key2',value2(),'key3',value3(),'key4',value4());
> 
> sub testfunc
>   {
>     foreach my $elem (@_)
>       {
> 	print "Got ".((defined $elem) ? "'$elem'" : 'undef')."\n";
>       }
>   }
> -------------------------------------------------------
> It produces the following:
> Got 'key1'
> Got 'value1'
> Got 'key2'
> Got 'value2'
> Got 'key3'
> Got 'key4'
> Got undef
> ------------------------------------------------------
> Just wonder why I got NO VALUE AT ALL even undef for value3() call.

C<value3()> is called in array context,
so C<bad_func('key');> is called in array context,
and C<return> with no expression in array context returns C<()>.

Try
>     	return undef unless $hash{$key};
or
> 	sub value3 { return scalar bad_func('key3'); }
or 
> 	testfunc('key1',value1(),'key2',value2(),'key3',(scalar value3()),\
>	'key4',value4());
 
Robin

-- 
Robin Barker                        | Email: Robin.Barker@npl.co.uk
CMSC, Building 10,                  | Phone: +44 (0) 20 8943 7090
National Physical Laboratory,       | Fax:   +44 (0) 20 8977 7091
Teddington, Middlesex, UK. TW11 OLW | WWW:   http://www.npl.co.uk

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About