Coercion
Explore Perl's coercion mechanisms to understand how variables handle multiple data types through context. Learn about boolean, string, numeric, and reference coercion alongside concepts like autovivification and dualvars. This lesson helps you grasp how Perl automatically converts types for efficient and flexible coding with data structures.
We'll cover the following...
Throughout the lifetime of a Perl variable, it may contain values of different types—strings, integers, rational numbers, and more. Instead of attaching type information to variables, Perl relies on the context provided by operators to determine how to handle values. Perl attempts to do what we mean (we may hear this referred to as DWIM for “Do what I mean” or “Dwimmery”), though we must be specific about our intentions. If we treat a value as a string, Perl will do its best to coerce that value into a string.
Boolean coercion
Boolean coercion occurs when we test the truthiness of a value, such as in an if or while condition. Numeric 0, undef, the empty string, and the string '0' all evaluate as false values. All other values, including strings that may be numerically equal to zero (such as '0.0', '0e', and '0 but true'), evaluate ...