rhavin
rhavin

Reputation: 1689

Perl: how do I return undef into a list?

I have a little problem in Perl. Basically, i do something like this:

sub myFunction
{
    return (&myOtherFnA(),&myOtherFnB(),&myOtherFnC());
}
sub myOtherFnA() {return 'A';}
sub myOtherFnB() {return undef;}
sub myOtherFnC() {return 'C';}

my Problem is: when myOtherFnB() is returning undef, i want a list that has undef as 2nd element. But when myOtherFnB() does so, i just get a list with 2 elements, that of myOtherFnA() and that of myOtherFnC(). I get:

('A','C')

but i want to get:

('A', undef, 'C')

What syntax do I need to use to stop Perl from removing the return of myOtherFnB() from the list if it is undef and actually just put an element of undef into the list?

Upvotes: 0

Views: 120

Answers (1)

Borodin
Borodin

Reputation: 126722

I don't know what makes you think you're not getting undef in the list. However, there are a number of problems with your code

  • Don't use an ampersand & when defining subroutines — it is a syntax error

  • Don't use an ampersand when calling subroutines. That hasn't been necessary since Perl 4 over twenty years ago

  • Don't use prototypes (the parentheses after the subroutine name in the definition) as they don't do what you think, and they're meant for something quite specialised

  • Don't use upper case letters in local identifiers: they are reserved for global identifiers like package names

This rewrite of your code fixes the syntax errors and corrects the above problems. As you see, the second element of the returned list is undef

use strict;
use warnings;

sub my_function {
  return (
    my_other_function_a(),
    my_other_function_b(),
    my_other_function_c()
  );
}

sub my_other_function_a {
  return 'A';
}

sub my_other_function_b {
  return undef;
}

sub my_other_function_c {
  return 'C';
}


use Data::Dump;
dd [ my_function ];

output

["A", undef, "C"]

Upvotes: 7

Related Questions