davido has asked for the wisdom of the Perl Monks concerning the following question:
$flag ? $on : $off = $value;
And in fact, this works too:
$flag ? @array1 : @array2 = qw/This that the other/;
This works too.......
sub testthis { $_[0] = "Hi mom.\n"; } testthis ( $flag ? $yes : $no ); foreach ( $yes, $no ) { print "$_\n" if defined $_; }
But things break down in this push example:
my $condition = int rand 2; my ( @array1, @array2 ); my $stuff = "This, that, and the other"; push( ( $condition ? @array1 : @array2 ), $stuff );
That example gives a big fat compilation error.
I wonder if it has anything to do with the fact that neither of these succeed in modifying the parameter:
# First example; nothing gets assigned to @array; my @array; sub testthis { @_ = qw/This that and the other/; } testthis ( @array ); # Second example; nothing gets assigned to @array1 or @array2. # But no compiletime errors are generated either: my $condition = int rand 2; sub testthis { @_ = qw/This that and the other/; } my ( @array1, @array2 ); testthis( $condition ? @array1 : @array2 );
In a way, it seems like the ternary behavior within push must be related to the behavior of trying to assign to modify the contents of an array passed as a parameter to a sub. But the push version generates a compiletime error, and the non-push version just doesn't perform the modification of the parameter.
Has DWIM broken down? Is this defined behavior? I haven't found the trinary / push behavior documented. Perhaps I've missed something, but it's interesting to ponder anyway.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Trinary operator can't be used as first argument of push
by BrowserUk (Patriarch) on Dec 25, 2003 at 23:45 UTC | |
|
Re: Trinary operator can't be used as first argument of push
by NetWallah (Canon) on Dec 26, 2003 at 06:19 UTC | |
|
Re: Trinary operator can't be used as first argument of push
by grinder (Bishop) on Dec 26, 2003 at 15:47 UTC | |
|
Re: Trinary operator can't be used as first argument of push
by diotalevi (Canon) on Dec 26, 2003 at 03:05 UTC | |
|
Re: Trinary operator can't be used as first argument of push
by ysth (Canon) on Dec 26, 2003 at 21:18 UTC |