Replacing deprecated “defined(@array)” in a ternary operation

后端 未结 3 1200
南笙
南笙 2021-01-28 01:07

I have the following code which needs to be corrected, as defined(@array) is deprecated in the latest Perl.

my @inputs = (
    ( defined @{$padSrc-         


        
相关标签:
3条回答
  • 2021-01-28 01:35

    defined(@array) has never done what it looks like it does. It always just returns whether @array is non-empty.

    perl5.10.1 -E 'say defined(@foo)'                # ""
    perl5.10.1 -E '@foo=(); say defined(@foo)'       # ""
    perl5.10.1 -E '@foo=(42); say defined(@foo)'     # "1"
    perl5.10.1 -E '@foo=(undef); say defined(@foo)'  # "1"
    

    Anywhere that you test defined(@array) in your code, you can replace it with @array != 0 or scalar(@array) and your code will work exactly the same (plus or minus some deprecation warnings).

    As if (condition) ... or (condition) ? expr1 : expr2 or while (condition) always evaluate condition in scalar context, the scalar is optional in these constructions, and you can replace, say if (defined(@foo)) with if (@foo).

    0 讨论(0)
  • 2021-01-28 01:39

    You do not say what Perl version you use, so the following may work (if using Perl 5.10 or later) or not (if you are stuck with older versions), and since it is not very clear why you used defined in the first place:

     my @inputs = (
        @{$padSrc->{inouts} // []},
        @{$padSrc->{inputs} // []}
    );
    

    or even simpler:

    my @inputs = map { @{$padSrc->{$_} // []} } qw/inouts inputs/;
    
    0 讨论(0)
  • 2021-01-28 01:51

    That's much more concisely written this way

    my @inputs = ( @{ $padSrc->{inouts} }, @{ $padSrc->{inputs} } );
    
    0 讨论(0)
提交回复
热议问题