Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Accept User Input in if-else statement

I am accepting User Input in an If-Else block. Check Code:

if ( $svr == 1 ) {
    print "Enter Datbase Name\n";
    my $db = <>;
    chomp($db);
} elsif ( $svr == 2 ) {
    print "Enter Data Source Name (DSN)\n";
    my $db = <>;
    chomp($db);
}

When I am referring to $db in a later statement, I am getting the following error:

"Use of uninitialized value $db"

This is the statement in which I am using $db that is causing the error:

my $data_source = 'DBI:mysql:' . $db . ':' . $host;

Please help

like image 927
Amey Avatar asked Dec 06 '25 18:12

Amey


1 Answers

The first $db is scoped to the "then" block, and teh second $db is scoped to the "else" block. You need declare the $db var before the if.

my $db;
if($svr==1) {
 print "Enter Datbase Name\n";
 $db=<>;
 chomp($db);
} elsif($svr==2) {
 print "Enter Data Source Name (DSN)\n";
 $db=<>;
 chomp($db);
}
like image 50
Nate Avatar answered Dec 08 '25 12:12

Nate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!