Steve Bertrand wrote:
[ forgive me if it was sent twice. My first should be bounced as bad
sender addr ].
Besides consistently forgetting how to properly spell "ternary", I
can't, for some reason, embed it's use into my brain no matter how much
I read.
It is "borrowed" from the C programming language where it is limited to
use only as an rvalue expression and only with simple expressions. In
Perl you can use it as either an rvalue or an lvalue and in either
scalar or list context and with code blocks using the do{CODE BLOCK}
construct (although the latter is not usually recommended.)
Perhaps if someone could show me the way against a personal code snip, I
may finally "get it". What would this look like:
my $gst = $self->query->param( "gst${item_num}" );
my $pst = $self->query->param( "pst${item_num}" );
if ( $gst eq 'Yes' ) {
$gst = $self->tax_rate( 'gst' );
}
else {
$gst = 0;
}
my $gst = $self->query->param( "gst$item_num" ) eq 'Yes'
? $self->tax_rate( 'gst' )
: 0;
if ( $pst eq 'Yes' ) {
$pst = $self->tax_rate( 'pst' );
}
else {
$pst = 0;
}
my $pst = $self->query->param( "pst$item_num" ) eq 'Yes'
? $self->tax_rate( 'pst' )
: 0;
...in some cases I get it ( when reading code ). Then, shortly after
when I try it, my code breaks.
I'm thinking that I'm running into a precedence issue, but normally I
don't have so much trouble remembering a seemingly simple idiom.
Recently, I read this:
my $args = ( ref $_[0] eq 'HASH' ) ? shift : {} ;
Disregarding ( but acknowledging ) it's accompanying comment, is it fair
to rephrase it as such ( for my own understanding )?:
- if $_[0] is a hashref, shift @_ , and assign it to $args
- otherwise, assign an empty hashref ( anonymous ) to $args
Pretty close, yes. Assuming that that code in inside a subroutine and
shift is not operating on @ARGV instead. BTW, the parentheses are
redundant as there is no precedence problem without them in that example.
Some Examples:
- rvalue with scalars:
my $variable = $something < 3 ? 'first' : 'second';
- rvalue with lists:
my @stuff = $something < 3 ? 'a' .. 'z' : 'A' .. 'Z';
- normally lists require parentheses:
my @stuff = $something < 3 ? ( 'a', 'b', 'c' ) : ( 'A', 'B', 'C' );
- lvalue with scalars:
( $something < 3 ? $first : $second ) = 'value';
- lvalue with arrays:
( $something < 3 ? @first : @second ) = qw/ a very small list /;
- the same with push() using references
push @{ $something < 3 ? \...@first : \...@second }, qw/ a very small list /;
John
--
Those people who think they know everything are a great
annoyance to those of us who do. -- Isaac Asimov
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/