How do I check if a Perl scalar variable has been initialized?

后端 未结 5 1747
别跟我提以往
别跟我提以往 2020-12-13 12:59

Is the following the best way to check if a scalar variable is initialized in Perl, using defined?

my $var;

if (cond) {
    $var = \"string1\";         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-13 13:50

    It depends on what you plan on doing with the variable whether or not it is defined; as of Perl 5.10, you can do this (from perl51000delta):

    A new operator // (defined-or) has been implemented. The following expression:

     $a // $b
    

    is merely equivalent to

    defined $a ? $a : $b
    

    and the statement

    $c //= $d;
    

    can now be used instead of

    $c = $d unless defined $c;
    

提交回复
热议问题