What is “stringification” in Perl?

后端 未结 3 662
误落风尘
误落风尘 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:29

    Just adding to the above answer, to draw an analogy with java ...

    Much similar to Object.toString() in Java. Omni-present by default but could be over-ridden when required.

    0 讨论(0)
  • 2021-02-01 04:32

    Stringification methods are called when an object is used in a context where a string is expected. The method describes how to represent the object as a string. So for instance, if you say print object; then since print is expecting a string, it's actually passing the result of the stringify method to print.

    0 讨论(0)
  • 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;`
    
    0 讨论(0)
提交回复
热议问题