[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [Fun With Perl] Does this count as a one-liner?



On Tue, Jun 15, 1999 at 05:07:54PM -0400, tomr@aceldama.com wrote:
> Here's my favourite <<HERE idiom for inline SQL from a snazzy mod_perl
> shopping cart.
> 
>     $query = (unindent ($quantity < 1)
>     ? <<""
>         DELETE FROM Contents
>         WHERE cartnum = '$cartnum'
>           AND itemid = '$itemid';
> 
>     : <<""
>         UPDATE Contents
>         SET quantity = $quantity
>         WHERE cartnum = '$cartnum'
>           AND itemid = '$itemid';
> 
>     );
> 
> For compactness, I believe it could be written as:
> 
>     $query = (unindent ($quantity < 1) ? <<""
>         DELETE FROM Contents
>         WHERE cartnum = '$cartnum'
>           AND itemid = '$itemid';
> 
>     : <<"");
>         UPDATE Contents
>         SET quantity = $quantity
>         WHERE cartnum = '$cartnum'
>           AND itemid = '$itemid';

Or:

    $query = (unindent ($quantity < 1) ? <<"" : <<"");
        DELETE FROM Contents
        WHERE cartnum = '$cartnum'
          AND itemid = '$itemid';

        UPDATE Contents
        SET quantity = $quantity
        WHERE cartnum = '$cartnum'
          AND itemid = '$itemid';


> Of course that is a bit more dangerous since the dangling ); visually
> closed the line. I suppose I could eliminate cut-and-pasted redundancy
> with the more-entertaining:
> 
>     $query = (unindent ($quantity < 1)
>     ? <<''
>         DELETE FROM Contents
> 
>     : <<""
>         UPDATE Contents
>         SET quantity = $quantity
> 
>     . <<""
>         WHERE cartnum = '$cartnum'
>           AND itemid = '$itemid';
> 
>     );
> 
> Can anyone comment on how operator precedence will affect this?  I
> wouldn't want $query to ever end up being just 'DELETE FROM Contents'!

Then you'd better not use that last one, because, as you guessed, the
precedence is all wrong.  . has higher precedence than ?:.

You meant the following:

    $query = ( ( unindent ($quantity < 1)
    ? <<''
        DELETE FROM Contents

    : <<""
        UPDATE Contents
        SET quantity = $quantity

    ) . <<""
        WHERE cartnum = '$cartnum'
          AND itemid = '$itemid';
    );

Note the extra parentheses.

> Also, do I really save any CPU time with the <<'' rather than <<"" in
> the first part of this last example?

Probably not enough to notice.

Ronald

==== Want to unsubscribe from this list? (Don't you love us anymore?)
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org