Nate the Noob Nate the Noob - 1 year ago 88
Perl Question

Identify empty string in Perl

There is probably an easy solution to this, but I can't figure it out. I am looking to:

  • take a CSV file into an array

  • loop through the array and split fields into variables

  • if the array field is empty then set the variable to "N/A"

Note: It is only setting the
to "
" that I cannot get working.

For example:

foreach $var (@list) {

($name,$date,$size, etc...)=split(/,\"/,$var);


How would I set
to "
" 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.

Answer Source

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';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download