Open In App

Coercions in Perl

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:

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

Article Tags :