Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks,

Can anybody please explain to me what this snippet of code is supposed to do:
my $tempport = $args{DOUBLE_BYTE} =~ /y/i ? DB_CATPORT : SB_CATPORT ;
Thanks a lot,
Anonymous Monk

Replies are listed 'Best First'.
Re: Snippet explanation please
by davidrw (Prior) on Jul 04, 2005 at 14:39 UTC
    In English: If the string $args{DOUBLE_BYTE} has a 'y' or 'Y' in it, sets $tempport to the constant DB_CATPORT, otherwise sets it to SB_CATPORT.

    In Perl:
    my $tempport; # declare var if( $args{DOUBLE_BYTE} =~ /y/i ) # try to match with a regex # regex is just looking for 'y' # the /i means case-insensitive { $tempport = DB_CATPORT; # Set to DB_CATPORT } else { $tempport = SB_CATPORT; # Set to SB_CATPORT }
    The key uses here are the regex (perldoc perlre) and the ternary operation (perldoc perlop).

    Update: Note that $args{DOUBLE_BYTE} represents the value in the %args hash for key 'DOUBLE_BYTE'. (though i guess DOUBLE_BYTE could be a constant, in which case the key is really the constant's value.) Update: thanks Errto! Note to self: don't overthink.
      (though i guess DOUBLE_BYTE could be a constant, in which case the key is really the constant's value.)
      Actually, it's not:
      use constant a => 'b'; my %foo; $foo{a} = "x"; print keys %foo; __END__ a
      By that logic, it should print 'b' instead. Remember, "constants" in Perl are really just subroutines, not C-style macros. The rule that a bareword as a hash key is always treated as a string applies whether or not there's a subroutine or constant with that name defined.
Re: Snippet explanation please
by holli (Abbot) on Jul 04, 2005 at 14:36 UTC
    my $tempport; if ( $args{DOUBLE_BYTE} =~ /y/i ) { $tempport = DB_CATPORT; } else { $tempport = SB_CATPORT; }


    holli, /regexed monk/
Re: Snippet explanation please
by rev_1318 (Chaplain) on Jul 04, 2005 at 14:40 UTC
    UPdate: again, to late :(

    without knowing the rest off the code, ussumtions have to be made, but my guess:

    if $args{DOUBLE_BYTE} contains a 'y' character (case doesn't matter), $tempport is set to the constant value DB_CATPORT.
    Otherwise, $tempport is set to the constant SB_CATPORT.

    the following code does the same:

    my $tempport; if ( $args{DOUBLE_BYTE} =~ /y/i ) { $tempport = DB_CATPORT } else { $tempport = SB_CATPORT }

    Paul

Re: Snippet explanation please
by neniro (Priest) on Jul 04, 2005 at 14:37 UTC