Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Perl string become undefined?

Tags:

string

perl

What is the proper way to concatenate several scalar values into one Perl string?

The following code is deliberately a series of statements for debugging reasons.

my $bill_record;

$bill_record = $acct_no . " |";

$bill_record = $bill_record . defined($w_ptWtrMtrRecRef->{"mtr_addr_no"})  ?  $w_ptWtrMtrRecRef->{"mtr_addr_no"} : " "  . " |" ;

$bill_record = $bill_record . defined($w_ptWtrMtrRecRef->{"mtr_addr_str"}) ? $w_ptWtrMtrRecRef->{"mtr_addr_str"} : " " . " |" ;

$bill_record = $bill_record . defined($w_ptWtrMtrRecRef->{"mtr_addr_apt"}) ? $w_ptWtrMtrRecRef->{"mtr_addr_apt"} : " " . " |"  ;

$bill_record = $bill_record . $issue_date . " |";

The | character is serving as a delimiter. Each line will be '\n terminated.

After the last line $bill_record = $bill_record . $issue_date . " |"; This error appears:

Use of uninitialized value $bill_record in concatenation (.) or string at /home/ics/include/WsBillFunc.pm line 1022.
 at /home/ics/include/WsBillFunc.pm line 1022

$issue_date is defined when assigned.

What could be causing $bill_record to become undefined, and what is the proper way to concatenate a bunch of scalar values into one string?

like image 420
octopusgrabbus Avatar asked Mar 15 '26 02:03

octopusgrabbus


1 Answers

I don't know specifically why $bill_record is undefined. But if I understand what you're trying to do, you're running into a precedence problem: the ?: operator has lower precedence than concatenation ., so that

$bill_record = $bill_record . defined($w_ptWtrMtrRecRef->{"mtr_addr_no"})  ?  $w_ptWtrMtrRecRef->{"mtr_addr_no"} : " "  . " |" ;

is treated as

$bill_record = ($bill_record . defined($w_ptWtrMtrRecRef->{"mtr_addr_no"}))  ?  $w_ptWtrMtrRecRef->{"mtr_addr_no"} : (" "  . " |") ;

which I suspect is not what you want. Try adding parentheses:

$bill_record = $bill_record . (defined($w_ptWtrMtrRecRef->{"mtr_addr_no"})  ?  $w_ptWtrMtrRecRef->{"mtr_addr_no"} : " ")  . " |" ;

(Or use .= as another commenter suggested.)

like image 94
ajb Avatar answered Mar 16 '26 17:03

ajb



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!