There is probably an easy solution to this, but I can't figure it out. I am looking to:
Note: It is only setting the $variable
to "N/A
" that I cannot get working.
For example:
foreach $var (@list) {
($name,$date,$size, etc...)=split(/,\"/,$var);
}
How would I set $date
to "N/A
" if the field in the array is empty?
so to produce:
$name = Jim
$date = N/A
$size = small
I hope this makes sense and is easy to fix. -Thanks
One can compare it with NULL(in Java, PHP etc.) and Nil(in Ruby). So basically when the programmer will declare a scalar variable and don't assign a value to it then variable is supposed to be contain undef value. In Perl, if the initial value of a variable is undef then it will print nothing.
There's no NULL in Perl. However, variables can be undef ined, which means that they have no value set. To check for definedness of a variable, use defined() , i.e. +1.
There is a strange scalar variable called $_ in Perl, which is the default variable, or in other words the topic. In Perl, several functions and operators use this variable as a default, in case no parameter is explicitly used.
Assuming the variable $date
is undefined when "empty":
if (!defined($date)) {
$date = 'N/A';
}
Or more concisely:
$date //= 'N/A';
Or if it really is an empty string, i.e. $date = '';
(this will also work in the case where $date
is undefined, but you don't want to use this if you only want to identify the case where it is undefined):
if ($date eq '') {
$date = 'N/A';
}
Or more concisely (note that this will also set $date
to N/A
if $date
is '0'
due to Perl's weak typing):
$date ||= 'N/A';
As far as your third bullet point and the actual question: to check for emptiness:
For empty string, you can either do the above-mentioned eq ""
, or you can check the string length: $var = "N/A" unless length($var);
;
For an undefined of empty string, in Perl 5.10 you can use the "defined-or" (//
) operator to do the short version: $var = "N/A" unless length($var // '');
In Perl before 5.10 where "defined-or" is not available, you will either have to spell out the defined check: $var = "N/A" unless defined $var && length($var);
... or, you can just stop caring about undefined warnings by turning them off (h/t brian d foy):
no warnings 'uninitialized';
$_ = "N/A" unless length($_) foreach ($name,$date,$size, etc...);
use warnings 'uninitialized'; # Always turn back on.
However, please note that you also should consider a different approach to the first two bullet points. Implementing your own CSV parser which is 100% correct is not trivial - for example, your sample code will break if any of the fields contain a double quote.
Instead, you should always use one of the standard Perl CSV parsers, such as Text::CSV_XS
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With