develooper Front page | perl.perl5.porters | Postings from August 2008

Re: unless(...) terser than if(!...)

Thread Previous | Thread Next
From:
Graham Barr
Date:
August 28, 2008 15:56
Subject:
Re: unless(...) terser than if(!...)
Message ID:
AA06C495-8748-4053-934F-74648DF1F59D@pobox.com

On Aug 28, 2008, at 4:45 PM, Nicholas Clark wrote:

> If I write this:
>
> $ ./perl -Ilib -MO=Concise -e 'print if !$a'
> 9  <@> leave[1 ref] vKP/REFC ->(end)
> 1     <0> enter ->2
> 2     <;> nextstate(main 1 -e:1) v:{ ->3
> -     <1> null vK/1 ->9
> 5        <|> and(other->6) vK/1 ->9
> 4           <1> not sK/1 ->5
> -              <1> ex-rv2sv sK/1 ->4
> 3                 <#> gvsv[*a] s ->4
> 8           <@> print vK ->9
> 6              <0> pushmark s ->7
> -              <1> ex-rv2sv sK/1 ->8
> 7                 <#> gvsv[*_] s ->8
> -e syntax OK
>
> it uses one more op than the semantically equivalent:
>
> $ ./perl -Ilib -MO=Concise -e 'print unless $a'
> 8  <@> leave[1 ref] vKP/REFC ->(end)
> 1     <0> enter ->2
> 2     <;> nextstate(main 1 -e:1) v:{ ->3
> -     <1> null vK/1 ->8
> 4        <|> or(other->5) vK/1 ->8
> -           <1> ex-rv2sv sK/1 ->4
> 3              <#> gvsv[*a] s ->4
> 7           <@> print vK ->8
> 5              <0> pushmark s ->6
> -              <1> ex-rv2sv sK/1 ->7
> 6                 <#> gvsv[*_] s ->7
> -e syntax OK
>
>
> Couldn't we optimise the former to the latter fairly easily?

But they can be subtly different in the presence of overload

{
   package foo;
   use overload "!" => sub { 1 }, "bool" => sub { 2 }, fallback => 1;
}

$a = bless [],'foo';

print "a\n" if $a;
print "b\n" if !$a;
print "c\n" unless $a;
print "d\n" unless !$a;

Graham.



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