Cool/useful short examples of Perl?

Abigail abigail at abigail.be
Thu Jun 9 16:08:45 BST 2011


On Thu, Jun 09, 2011 at 03:39:45PM +0100, David Matthewman wrote:
> 
> On 9 Jun 2011, at 15:16, David Landgren wrote:
> 
> > I had all the parts lying around, but didn't realise they were germane to the problem. So, thanks for the cogent explanation.
> 
> You're welcome. ;-)
> 
> This effect means that:
> 
>   if (!something)
> 
> and
> 
>   unless(something)
> 
> don't do the same thing either, whereas from the 'overloaded operator'
  point-of-view *as far as I can tell* they do the same thing. The 'unless'
  statement runs the overloaded '!' subroutine of the class in question,
  as opposed to doing a 'bool' conversion on the class and doing a logical
  NOT on the result of that, which is the other thing it *might* be expected
  to do.


Yeah. I though 'if (!something)' to call a '!' overload method, and
'unless (something)' to call a 'bool' or '""' overload method. They don't,
in either case a '!' overload method is called. In fact, it seems they
even compile down to the same code:

    $ perl -MO=Concise -we 'unless ($x) {1}'
    Name "main::x" used only once: possible typo at -e line 1.
    5  <@> leave[1 ref] vKP/REFC ->(end)
    1     <0> enter ->2
    2     <;> nextstate(main 3 -e:1) v:{ ->3
    -     <1> null vK/1 ->5
    4        <|> or(other->-) vK/1 ->5
    -           <1> ex-not sK*/1 ->4
    -              <1> ex-rv2sv sK/1 ->-
    3                 <$> gvsv(*x) s ->4
    -           <@> scope vK ->5
    -              <0> ex-nextstate v ->-
    -              <0> ex-const v ->-
    -e syntax OK

    $ perl -MO=Concise -we 'if (!$x) {1}'
    Name "main::x" used only once: possible typo at -e line 1.
    5  <@> leave[1 ref] vKP/REFC ->(end)
    1     <0> enter ->2
    2     <;> nextstate(main 3 -e:1) v:{ ->3
    -     <1> null vK/1 ->5
    4        <|> or(other->-) vK/1 ->5
    -           <1> ex-not sK/1 ->4
    -              <1> ex-rv2sv sK/1 ->-
    3                 <$> gvsv(*x) s ->4
    -           <@> scope vK ->5
    -              <0> ex-nextstate v ->-
    -              <0> ex-const v ->-
    -e syntax OK



Abigail


More information about the london.pm mailing list