What do you get if you evaluate a hash in scalar context?

前端 未结 5 2137
滥情空心
滥情空心 2020-12-03 07:20

Consider the following snippet:

use strict;
use warnings;

my %a = ( a => 1,
          b => 2,
          c => \'cucu\',
          d => undef,
            


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 07:47

    To focus too much on this fractional pattern (as an indicator for internal details of the hash), can be confusing. There is an aspect of the "scalar value" of a hash that is important for potentially every Perl program and that is, if it is considered true in Boolean context, see an example:

    if (%h) {
        print "Entries in hash:\n";
        for my $k (sort keys %h) {
            print "$k: $h{$k}\n";
        }
    }
    

    In perldoc perldata, section Scalar-values, you can read that

    [...] The Boolean context is just a special kind of scalar context where no conversion to a string or a number is ever performed.

    and, some paragraphs later,

    If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true [...]

提交回复
热议问题