Jonjon Negrite
Jonjon Negrite

Reputation: 1

undef variable from "if" condition

I have a problem condition in Perl. I hope someone can help me.

my $bCommType = 'none';

my %commTypes = (
    'none'              => '0',
    'public'            => '1',
    'custom_percentage' => '2',
    'custom_permeg'     => '2',
    'custom_flat'       => '2',
);

my %rateTypes = (
    'custom_percentage' => '%',
    'custom_permeg'     => '$',
    'custom_flat'       => 'FLAT',
    'none'              => 'none',
);

my $commrate = $rateTypes{$bCommType} if ( $commTypes{$bCommType} == 2 );

my output in $commrate is undef, can someone help me identify the issue?

Upvotes: 0

Views: 434

Answers (3)

Kevin Ng
Kevin Ng

Reputation: 2174

This is a better way of using a conditional declaration. This method will work whether if you are working with Perl, JavaScript, Java or PHP. Where I declared the condition, the statement before the question mark is the condition. The value right after the question mark is the value that will be assigned to the variable when the condition evaluates to be true. The value after the column is the value that will be assigned to the variable if the statement evaluates to be false.

use strict;
my $bCommType = 'none';

my %commTypes = (
    'none'              => '0',
    'public'            => '1',
    'custom_percentage' => '2',
    'custom_permeg'     => '2',
    'custom_flat'       => '2',
);

my %rateTypes = (
     'custom_percentage' => '%',
     'custom_permeg'     => '$',
     'custom_flat'       => 'FLAT',
     'none'              => 'none',
);

my $commrate = $commTypes{$bCommType} == 2? $rateTypes{$bCommType} : "false value";

print $commrate;

Upvotes: 0

Borodin
Borodin

Reputation: 126722

You set $commrate to $rateTypes{$bCommType} if the value of $commTypes{$bCommType} is 2. But $bCommType is none and $commTypes{none} is zero, so the assignment doesn't happen and $commrate is left undefined

That is the root of your problem, but aside from this, you shouldn't declare a variable conditionally. It does all sorts of strange and undefined things if you try. As simbabque has said, you need to declare the variable separately and make just the assigmnent conditional, but in this case the result will be the same for the reason I described above

Upvotes: 2

simbabque
simbabque

Reputation: 54323

You are using a conditional declaration. That's deprecated. Perl is probably giving you a warning (you are using use warnings, right?).

Move the declaration into its own line, provide a default, and do the assignment with the condition in a new line.

my $commrate = 'default'; # it's not clear which %commTypes is the default
$commrate = $rateTypes{$bCommType} if ($commTypes{$bCommType} == 2);

You need to provide a default or starting value because new variables in Perl always start out as undef.

Upvotes: 2

Related Questions