Open In App

Coercions in Perl

Last Updated : 28 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In Perl, there are values of different types like strings, integers, rational numbers, and more. Coercion is responsible for converting one data type of data or object to another, behind the scenes where we magically just get what we want. It generally refers to “implicit type conversion” which is also one of the ways of changing an entity of one data type into another.

The most common form of coercion is the overload pragma, and its string overloading in Perl programming. In this case, our object is automatically coerced into a string (within Perl itself).
The type of coercion intended for high order coercion is the Params::Coerce which is mainly used in subroutine and method parameters.

Types of Coercions

The types of coercion are explained below:

  • Boolean Coercion: Boolean coercion is useful to test the truthiness of value just like in an if or while condition. All the numeric 0, undef, the empty string, and the string ‘0’ evaluate as false values. All the other values including strings which are numerically equal to zero (like ‘0.0’, ‘0e’ and ‘0 but true’)- evaluate as true values.
    When a scalar consists of both string and numeric components, Perl preferably checks the string component for Boolean truth. ‘0 but true’ evaluates to zero numerically, but is not an empty string, hence it gets evaluated as a true value in a Boolean context.

    Example:

    say ?^True; # Falsesay ?^'';   # Truesay ?^0;    # Truesay ?^42;   # False

    (The ? prefix operator is the Boolean coercion operator. It converts its operand to a Boolean value.)

  • String Coercion: String coercion comes into action when we use string operators like comparisons (eq and cmp), concatenation, split, substr, and regular expressions, and also while using a value or an expression as a hash key. The undefined value is then stringified to an empty string but produces a “use of uninitialized value” warning. Numbers stringify to string which contains their values. (stringify = to return a string)

    Example:




    use strict;
    use warnings;
    my $x = "4T"; # string
    my $y = 3;    # integer
    my $z = $x.$y;
    print $z;     # coerced

    
    

    Output:

    4T3
  • Numeric Coercion: Numeric coercion occurs when we use a numeric comparison operator such as == and <=>, while performing mathematical operations or while using an expression or a value as an array or list index. The undefined value then numifies to zero and gives us a “Use of uninitialized value” warning. The strings which do not start with any numeric portion numify to zero and give us a warning of “Argument isn’t numeric”. And the ones which begin with character allowed in numeric literals numify to the values specified and produce no warning. (numify = to return a number).
    There’s also a function in Perl function which uses the same parsing rules as the Perl grammar to extract a number from a string that is looks_like_number() which is included in the core module Scalar::Util.

    Example:




    my $a = "23B";
    $a +=0;
      
    # string part has been removed automatically.
    print $a

    
    

    Output:

    23
  • Reference Coercion: When we use a dereferencing operation on a non-reference, it turns a value into a reference. This process is known as Autovivification. This process comes handy while manipulating nested data structures.
    Example:




    my %users;
    $users{John}{id} = 128;
    $users{Thomas}{id} = 129;

    
    

    Explanation: As we can see in this that the hash doesn’t contain values for John and Thomas but Perl has helpfully created hash references for them, assigning each of them a key/value pair keyed on id.

  • Cached Coercions: The internal representation of values in Perl stores both string and numeric values. Like when we stringify a value, it does not replace the numeric value rather it adds a stringified value to the internal representation which later consists of both the components. Similarly when we numify a string value, it populates the numeric value and leaves the string component untouched.
    For example: Certain Perl operators often prefer to use one value over the other (just like Boolean checks prefer strings). If there’s a value which has cached representation in a form that we don’t expect, then relying on an implicit conversion may produce some surprising results. Knowing how this occurs might help us to help us diagnose some odd situation.

Dualvars

Perl has a multi-component nature which is available to user in the form of dualvars. The function dualvar() is provided by the core module Scalar :: Util, which allows us to bypass Perl coercion and manipulate the string and numeric components of a value separately. 




use Scalar::Util qw(blessed dualvar set_prototype);
$foo = dualvar 10, "Geeksfor";
$num = $foo + 2;                   
$str = $foo . " Geeks";             
print "$num\n";
print $str;


Output:

12
Geeksfor Geeks


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads