What is “stringification” in Perl?

后端 未结 3 669
误落风尘
误落风尘 2021-02-01 04:18

In the documentation for the CPAN module DateTime I found the following:

Once you set the formatter, the overloaded stringification method will use th

3条回答
  •  面向向阳花
    2021-02-01 04:33

    "stringification" happens any time that perl needs to convert a value into a string. This could be to print it, to concatenate it with another string, to apply a regex to it, or to use any of the other string manipulation functions in Perl.

    say $obj;
    say "object is: $obj";
    if ($obj =~ /xyz/) {...}
    say join ', ' => $obj, $obj2, $obj3;
    if (length $obj > 10) {...}
    $hash{$obj}++;
    ...
    

    Normally, objects will stringify to something like Some::Package=HASH(0x467fbc) where perl is printing the package it is blessed into, and the type and address of the reference.

    Some modules choose to override this behavior. In Perl, this is done with the overload pragma. Here is an example of an object that when stringified produces its sum:

    {package Sum;
        use List::Util ();
    
        sub new {my $class = shift; bless [@_] => $class}
    
        use overload fallback => 1,
            '""' => sub {List::Util::sum @{$_[0]}}; 
    
        sub add {push @{$_[0]}, @_[1 .. $#_]}
    }
    
    my $sum = Sum->new(1 .. 10);
    
    say ref $sum; # prints 'Sum'
    say $sum;     # prints '55'
    $sum->add(100, 1000);
    say $sum;     # prints '1155'
    

    There are several other ifications that overload lets you define:

    'bool' Boolification    The value in boolean context   `if ($obj) {...}`
    '""'   Stringification  The value in string context    `say $obj; length $obj`
    '0+'   Numification     The value in numeric context   `say $obj + 1;`
    'qr'   Regexification   The value when used as a regex `if ($str =~ /$obj/)`
    

    Objects can even behave as different types:

    '${}'   Scalarification   The value as a scalar ref `say $$obj`
    '@{}'   Arrayification    The value as an array ref `say for @$obj;`
    '%{}'   Hashification     The value as a hash ref   `say for keys %$obj;`
    '&{}'   Codeification     The value as a code ref   `say $obj->(1, 2, 3);`
    '*{}'   Globification     The value as a glob ref   `say *$obj;`
    

提交回复
热议问题