A question on the Conditional Operator 
Author Message
 A question on the Conditional Operator

I'm working on a perl utility to keep track of phone numbers,
addresses, etc.  If called with no arguements, it prints out the full
list of names, sorted in ascending order.  If it is called with an
arguement, it only prints out those names that match using /$arg/.
What I would like to do is:

        $findname ? write if (/$findname/o) : write;

but perl doesn't like this.  And if I invert it to:

        (!$findname) ? write : write if ($findname/o);

it doesn't work, although it doesn't complain about the conditional
now.  Would it be too hard to make the conditional operator work on
blocks?  Such as:

        $findname ? { ... } : { ... };

Thanks.

                        John
--
Life is death, death is life, but a good ham sandwich will last you a lifetime.
-------------------------------------------------------------------------------

John Stoffel     | 508-831-5512 (work)     | Worcester, MA  01609



Mon, 02 Oct 1995 22:35:25 GMT  
 A question on the Conditional Operator
:
: I'm working on a perl utility to keep track of phone numbers,
: addresses, etc.  If called with no arguements, it prints out the full
: list of names, sorted in ascending order.  If it is called with an
: arguement, it only prints out those names that match using /$arg/.
: What I would like to do is:
:
:       $findname ? write if (/$findname/o) : write;
:
: but perl doesn't like this.  And if I invert it to:
:
:       (!$findname) ? write : write if ($findname/o);
:
: it doesn't work, although it doesn't complain about the conditional
: now.  Would it be too hard to make the conditional operator work on
: blocks?  Such as:
:
:       $findname ? { ... } : { ... };

Use either of

        $findname ? /$findname/o && write : write;
        $findname ? do { write if /$findname/o} : write;

It's not syntactically possible to allow bare {} anywhere in an
expression, hence the existence of the "do {}" construct.  The reason
it's not possible is that the lexer wouldn't know whether to expect a
term or an operator after the block:

        { 1; }
        +$foo;          # Is that a unary or a binary plus?

In real Perl, it's always a unary plus.  You have to say

        do { 1; }
        +$foo;

to mean the other.

Larry



Sat, 07 Oct 1995 11:45:35 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Ternary Conditional Operator Question

2. newbie questions re conditional operators

3. Conditional Operator behavior?

4. Three Operand Conditional Operator

5. push onto trinary conditional operator?

6. Q: conditional operator and variable assignment

7. ternary conditional operator

8. conditional operator "?:"

9. problem parsing conditional operator.

10. conditional replacement (newbie question)

11. range operator w/ while operator

12. += operator produces error, = operator doesn't?

 

 
Powered by phpBB® Forum Software