Perl Onion

  •   AUTHORS
  •   CATEGORIES
  • #   TAGS

Use the logical-or and defined-or operators to provide default subroutine variable behaviour

Jul 6, 2013 by David Farrell

Perl subroutines do not have signatures so variables must be initialized and arguments assigned to them inside the subroutine code. This article describes two useful shortcuts that can simplify this process.

One trick that Perl programmers use is the logical-or operator (‘||’) to provide default behaviour for subroutine arguments. The default behaviour will only occur if the argument is provided is false (undefined, zero or a zero-length string). Imagine that we’re developing a subroutine that processes data for car insurance quotes - we’ll need to collect some basic data such as the applicant’s date of birth, sex and number of years driving. All of the arguments are mandatory - we can use the logical-or operator to return early if these arguments are false.

What this subroutine code does is assign the first element of the default array (@_) to $args using shift. By default shift will operate on @_, so there is no need to include it as an argument. Next the subroutine initializes and assigns the $dob and $sex variables. In both cases we use the logical-or (‘||’) operator to return early from the subroutine if these variables are false. This is a more concise code pattern than using an if statement block. We cannot use this trick to return early from the $years_driving variable as it may be provided as zero, which Perl treats as logical false but we want to keep. So in this case we have to first check if the argument was defined (which would include zero) and then use a ternary operator to either assign the value or return early.

Since version 5.10.0 Perl has has had the defined-or operator (‘//’). This will check if the variable is defined, and if it is not, Perl will execute the code on the right-side of the operator. We can use it to simplify our subroutine code:

In the modified code above, first we have included a line to use Perl 5.10.0 or greater - this will ensure that the version of Perl executing the code has the defined-or operator. Next we’ve simplified the code for $years_driving to use the logical-or operator. This will now accept zero as an argument, but return when $years_driving is undefined.

Default values

We can also use defined-or to provide default values for subroutine arguments. For example if we assumed that all users of our subroutine are male, we can change the $sex variable to default to ’M’.

Now if the $sex variable is undef, the process_quote_data subroutine will assign ’M’ as it’s value.

You can read more about these operators and in the perlop section of the official Perl documentation.

This article was originally posted on PerlTricks.com .

David Farrell

David is a professional programmer who regularly tweets and blogs about code and the art of programming.

Browse their articles

Something wrong with this article? Help us out by opening an issue or pull request on GitHub

To get in touch, send an email to [email protected] , or submit an issue to tpf/perldotcom on GitHub.

This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 Unported License .

Creative Commons License

Perl.com and the authors make no representations with respect to the accuracy or completeness of the contents of all work on this website and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. The information published on this website may not be suitable for every situation. All work on this website is provided with the understanding that Perl.com and the authors are not engaged in rendering professional services. Neither Perl.com nor the authors shall be liable for damages arising herefrom.

Perl Programming/Operators

  • 1 Introduction
  • 2.1.1 Binary
  • 2.1.2 Unary
  • 2.2 Assignment
  • 2.3 Comparison
  • 2.4.1 Conditionals
  • 2.4.2 Partial evaluation
  • 2.5 Bitwise
  • 2.7 Comparing strings
  • 2.8 File Test
  • 2.10 Precedence
  • 2.11 The smart match operator
  • 2.12.1 The doubledollar
  • 2.12.2 The arrow operator

Introduction [ edit | edit source ]

Perl's set of operators borrows extensively from the C programming language . Perl expands on this by infusing new operators for string functions ( .= , x , eq , ne , etc.). C by contrast delegates its subset of Perl functionality to a library strings.h , and ctype.h , and includes no such functionality by default compilation. Perl also includes a highly flexible Regex engine inspired by Sed with improvements to standard POSIX regexes, most notably the support of Unicode.

The operators [ edit | edit source ]

Arithmetic [ edit | edit source ].

Most arithmetic operators are binary operators; this means they take two arguments. Unary operators only take one argument. Arithmetic operators are very simple and often transparent.

Binary [ edit | edit source ]

All the basic arithmetic operators, addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ), and the modulus operator % exist. Modulus returns the remainder of a division ( / ) operation.

The exponentiation operator is ** . It allows you to raise one value to the power of another. If you raise to a fraction you will get the root of the number. In this example the second result when raised to the power of 2 should return 2 ( (2**(1/2))**2 = 2 ).

The function sqrt is provided for finding a square root. Other fractional powers (i.e., (1/5), (2/13), (7/5), and similar) are suitably found using the ** operator.

Unary [ edit | edit source ]

The auto-decrement ( -- ), and auto-increment ( ++ ) operators are unary operators. They alter the scalar variable they operate on by one logical unit. On numbers, they add or subtract one. On letters and strings, only the auto-increment shift one up in the alphabet, with the added ability to roll-over. Operators that come in post- and pre- varieties can be used two ways. The first way returns the value of the variable before it was altered, and the second way returns the value of the variable after it was altered.

Assignment [ edit | edit source ]

The basic assignment operator is = that sets the value on the left side to be equal to the value on the right side. It also returns the value. Thus you can do things like $a = 5 + ($b = 6) , which will set $b to a value of 6 and $a to a value of 11 (5 + 6). Why you would want to do this is another question.

The assignment update operators from C, += , -= , etc. work in perl. Perl expands on this basic idea to encompass most of the binary operators in perl.

Comparison [ edit | edit source ]

Perl uses different operators to compare numbers and strings. This is done, because in most cases, Perl will happily stringify numbers and numify strings. In most cases this helps, and is consistent with Perl's DWIM Do-What-I-Mean theme. Unfortunately, one place this often does not help, is comparison.

Logical [ edit | edit source ]

Perl has two sets of logical operators, just like the comparison operators, however not for the same reason.

The first set (sometimes referred to as the C-style logical operators, because they are borrowed from C) is && , || , and ! . They mean logical AND, OR, and NOT respectively. The second set is and , or , and not .

The only difference between these two sets is the precedence they take (See Precedence ). The symbolic operators take a much higher precedence than the textual.

Conditionals [ edit | edit source ]

Most of the time, you will be using logical operators in conditionals.

In this case, you could safely substitute and for && and the conditional would still work as expected. However, this is not always the case.

This, however, is completely different.

Most people prefer to use C-style logical operators and use brackets to enforce clarity rather than using a combination of textual and C-style operators (when possible), which can be very confusing at times.

Partial evaluation [ edit | edit source ]

Partial evaluation (or "short circuiting") is the property of logical operators that the second expression is only evaluated, if it needs to be.

This also works with logical OR statements. If the first expression evaluates as true, the second is never evaluated, because the conditional is automatically true.

This becomes useful in a case like this:

Here, if the foo() subroutine returns false, "foo() failed\n" is printed. However, if it returns true, "foo() failed\n" is not printed, because the second expression ( print "foo() failed\n" ) does not need to be evaluated.

Bitwise [ edit | edit source ]

These operators perform the same operation as the logical operators, but instead of being performed on the true/false value of the entire expressions, it is done on the individual respective bits of their values.

  • & (bitwise AND)
  • | (bitwise OR)
  • ^ (bitwise XOR)
  • ~ (bitwise NOT)

The left and right shift operators move the bits of the left operand (e.g. $a in the case of $a << $b) left or right a number of times equal to the right operand ($b). Each move to the right or left effectively halves or doubles the number, except where bits are shifted off the left or right sides. For example, $number << 3 returns $number multiplied by 8 (2**3).

  • << (left shift)
  • >> (right shift)

String [ edit | edit source ]

The string concatenation operator is . , not + that some other languages use.

There is a repeat operator for strings ( x ) that repeats a string a given number of times.

Comparing strings [ edit | edit source ]

To compare strings, use eq and ne instead of == or != respectively. You can also look for a substring with substr() , or pattern-match with regular expressions.

File Test [ edit | edit source ]

Other [ edit | edit source ].

The range operator (..) returns a list of items in the range between two items; the items can be characters or numbers. The type of character is determined by the first operand; the code:

Outputs (Newlines added for readability):

Note that the case is defined by the first operand, and that the 1..'a' and (10..-10) operations return empty list.

Precedence [ edit | edit source ]

Precedence is a concept that will be familiar to anyone who has studied algebra or coded in C/C++. Each operator has its place in a hierarchy of operators, and are executed in order. The precedence of perl operators is strict and should be overridden with parentheses, both when you are knowingly going against precedence and when you aren't sure of the order of precedence. For a complete listing of the order, check perlop .

The smart match operator [ edit | edit source ]

The smart match operator ~~ is new in perl 5.10. To use it, you'll need to explicitly say that you're writing code for perl 5.10 or newer. Its opposite operator ǃ~ matches smartly an inequality:

The smart match operator is versatile and fast (often faster than the equivalent comparison without ǃ~ or ~~ ). See smart matching in detail for the comparisons it can do. ~~ is also used in the given/when switch statement new in 5.10, which will be covered elsewhere.

Dereferencing [ edit | edit source ]

The doubledollar [ edit | edit source ].

A variable, previously referenced with the reference operator can be dereferenced by using a doubledollar symbol prefix:

The arrow operator [ edit | edit source ]

If the left hand operand of the arrow operator is an array or hash reference, or a subroutine that produces one, the arrow operator produces a look up of the element or hash:

perl defined or assignment operator

  • Book:Perl Programming

Navigation menu

Popular Articles

  • Perl Empty Array (Jan 05, 2024)
  • Perl Change Directory (Jan 05, 2024)
  • Perl Backticks (Jan 05, 2024)
  • Perl Vs Bash (Jan 05, 2024)
  • Perl Or Operator (Jan 05, 2024)

Perl or Operator

Switch to English

Table of Contents

Introduction

Explanation of the 'or' operator in perl, examples of the 'or' operator in perl, tips and tricks, common errors and how to avoid them.

  • Perl is a versatile and powerful programming language, used extensively in web development, system administration, bioinformatics, and many other areas. One of the fundamental aspects of Perl and indeed, any programming language is its ability to perform logical operations. In Perl, the 'or' operator holds a special place. This operator allows developers to test multiple conditions and execute code based on the result. This article will explore the Perl 'or' operator in detail, providing examples and tips to help you avoid common pitfalls.
  • In Perl, the 'or' operator is a logical operator that is used to perform logical OR operations. It returns true if either or both of the conditions being compared are true. If neither of the conditions is true, the operator will return false. Here is the basic syntax: perl condition1 or condition2 In this syntax, if condition1 is false, then Perl will evaluate condition2. If condition2 is true, then the whole expression is true. If both conditions are false, then the whole expression is false.
  • Let's look at a simple example to understand how the 'or' operator works in Perl: perl my $x = 10; my $y = 20; if ($x == 10 or $y == 30) { print "The condition is true\n"; } else { print "The condition is false\n"; } In this example, the 'or' operator is used to check two conditions. The first condition is whether $x is equal to 10 and the second condition is whether $y is equal to 30. Even though the second condition is false, the entire expression is true because the first condition is true, and so "The condition is true" is printed.
  • Understanding the 'or' operator is crucial for efficient Perl programming. Here are some tips and tricks that can help you: - Remember that the 'or' operator in Perl is a short-circuit operator. This means it evaluates the left-hand side first. If the left-hand side is true, it does not bother evaluating the right-hand side because the overall result will be true regardless. - Use parentheses to ensure the correct order of operations. Although 'or' has a low precedence, it can still be a good idea to use parentheses to make your intentions clear. - The 'or' operator can be used to provide default values. For example: perl my $value = $input or "default"; In this code, if $input is false (which in Perl can mean undefined, zero, or the empty string), then $value is set to "default".
  • One common mistake when using the 'or' operator in Perl is misunderstanding its precedence. The 'or' operator has lower precedence than many other Perl operators, which means it is often evaluated last. This can lead to unexpected results if you're not careful. For example, consider the following code: perl my $value = $input or "default"; You might expect this to assign the value of $input to $value, or "default" if $input is false. But because the assignment operator (=) has higher precedence than 'or', this will actually assign the value of $input to $value, and then evaluate $value or "default", which doesn't do anything useful. To avoid this, use parentheses: perl my $value = ($input or "default"); In conclusion, the 'or' operator in Perl is a powerful tool, but like any tool, it must be used correctly. By understanding how it works and being aware of common pitfalls, you can use the 'or' operator to write more efficient and effective Perl code.

Home » Perl Operators

Perl Operators

Summary : in this tutorial, you’ll learn about Perl operators including numeric operators, string operators, and logical operators.

Numeric operators

Perl provides numeric operators to help you operate on numbers including arithmetic, Boolean and bitwise operations. Let’s examine the different kinds of operators in more detail.

Arithmetic operators

Perl arithmetic operators deal with basic math such as adding, subtracting, multiplying, diving, etc. To add (+ ) or subtract (-) numbers, you would do something as follows:

To multiply or divide numbers, you use divide (/) and multiply (*) operators as follows:

When you combine adding, subtracting, multiplying, and dividing operators together, Perl will perform the calculation in an order, which is known as operator precedence.

The multiply and divide operators have higher precedence than add and subtract operators, therefore, Perl performs multiplying and dividing before adding and subtracting. See the following example:

Perl performs 20/2 and 5*2 first, therefore you will get 10 + 10 – 10 = 10.

You can use brackets () to force Perl to perform calculations based on the precedence you want as shown in the following example:

To raise one number to the power of another number, you use the exponentiation operator (**) e.g., 2**3 = 2 * 2 * 2. The following example demonstrates the exponentiation operators:

To get the remainder of the division of one number by another, you use the modulo operator (%).

It is handy to use the modulo operator (%) to check if a number is odd or even by dividing it by 2 to get the remainder. If the remainder is zero, the number is even, otherwise, the number is odd. See the following example:

Bitwise Operators

Bitwise operators allow you to operate on numbers one bit at a time. Think of a number as a series of bits e.g., 125 can be represented in binary form as 1111101 . Perl provides all basic bitwise operators including and (&), or (|), exclusive or (^) , not (~) operators, shift right (>>), and shift left (<<) operators.

The bitwise operators perform from right to left. In other words, bitwise operators perform from the rightmost bit to the leftmost bit.

The following example demonstrates all bitwise operators:

If you are not familiar with bitwise operations, we are highly recommended you check out bitwise operations on Wikipedia .

Comparison operators for numbers

Perl provides all comparison operators for numbers as listed in the following table:

All the operators in the table above are obvious except the number comparison operator  <=> which is also known as spaceship operator.

The number comparison operator is often used in sorting numbers. See the code below:

The number operator returns:

  • 1 if $a is greater than $b
  • 0 if $a and $b are equal
  • -1 if $a is lower than $b

Take a look at the following example:

String operators

String comparison operators.

Perl provides the corresponding comparison operators for strings. Let’s take a look a the table below:

String concatenation operators

Perl provides the concatenation ( . ) and repetition ( x ) operators that allow you to manipulate strings. Let’s take a look at the concatenation operator (.) first:

The concatenation operator (.) combines two strings together.

A string can be repeated with the repetition ( x ) operator:

The chomp() operator

The chomp() operator (or function ) removes the last character in a string and returns a number of characters that were removed. The chomp() operator is very useful when dealing with the user’s input because it helps you remove the new line character \n from the string that the user entered.

The <STDIN> is used to get input from users.

Logical operators

Logical operators are often used in control statements such as if , while ,  given, etc.,   to control the flow of the program. The following are logical operators in Perl:

  • $a && $b performs the logic AND of two variables or expressions. The logical && operator checks if both variables or expressions are true.
  • $a || $b performs the logic OR of two variables or expressions. The logical || operator checks whether a variable or expression is true.
  • !$a performs the logic NOT of the variable or expression. The logic ! operator inverts the value of the following variable or expression. In the other words, it converts true to false or false to true .

You will learn how to use logical operators in conditional statements such as  if ,  while  and  given .

In this tutorial, you’ve learned some basic Perl operators. These operators are very important so make sure that you get familiar with them.

An operator is the element affecting operands in a Perl expression and causes Perl to execute an operation on one of more operands. In the expression $a + 5 , $a and 5 are the operands and + is the operation causing the addition operation.

Perl programming can be accomplished by directly executing Perl commands at the shell prompt or by storing them in a text file with the .pl extension, and then executing it as a Perl script via perl file.pl .

Perl supports many operator types. Following is a list of frequently used operators.

Arithmetic Operators

Manipulate numeric scalar values.

  • + Addition - Adds the operand values from either side of the operator
  • - Subtraction - Subtracts the right operand from the left operand
  • - Negation - When taking a single operand (unary), it calculates the negative value
  • * Multiplication - Multiplies the operand values from either side of the operator
  • / Division - Divides the left operand by the right operand
  • % Modulus - Divides the left operand by the right operand and returns remainder
  • ** Exponent - Calculates the left operand to the power of the right operand

Comparison Operators

Used to compare two scalar string or scalar numeric values. Comparison or relational operators are discussed in the Conditional Decisions section of this tutorial. Please review them in that section.

Assignment Operators

Used to assign scalar or array data to a data structure.

  • = Simple assignment - assigns values from right side operands and operators to left side operand
  • += Addition and assign - add right operand to left operand and assign to left operand
  • -= Substract and assign - substract right operand from left operand and assign to left operand
  • *= Multiply and assign - multiply right operand by left operand and assign to left operand
  • /= Divide and assign - divide left operand by right operand and assign to left operand
  • %= Modulus and assign - divide left operand by right operand and assign remainder to left operand
  • **= Exponent and assign - calculates the left operand to the power of the right operand and assign to left operand
  • ++ Autoincrement - increases unary operand value by one. E.g. $x++ or ++$x gives 11
  • -- Autodecrement - decreases unary operand value by one. E.g. $x-- or --$x gives 9

Note that $x++ is considered post-autoincrement , and ++$x is considered pre-autoincrement :

  • $a = $x++ will assign $a with 10 and $x with 11 (autoincrement $x after assigning value to $a )
  • $a = ++$x will assign $x with 11 then assign $a with 11 (autoincrement $x before assigning value to $a )

Similarly with -- (autodecrement):

  • $a = $x-- will assign $a with 10 and $x with 0 (autodecrement $x after assigning value to $a )
  • $a = --$x will assign $x with 9 then assign $a with 9 (autodecrement $x before assigning value to $a )

Bitwise Operators

Manipulate numeric scalar values at the bit level.

Bitwise operators treat numeric operands as binary numbers and perform bit by bit operations. Scalars can be assigned with decimal, binary (with prefix 0b ) or hexadecimal (with prefix 0x ).

  • & AND - bitwise AND of the operand values from either side of the operator e.g. $b & $mask gives 0b1001
  • | OR - bitwise OR of the operand values from either side of the operator e.g. $b | $mask gives 0b1111
  • ^ XOR - bitwise XOR of the operand values from either side of the operator e.g. $b & $mask gives 0b1001
  • ~ NOT - bitwise INVERT (unary operator) inverts each bit of the left operand e.g. ~$b give 0b10100110
  • << SHIFT LEFT - bitwise SHIFT LEFT the left operand, right operand times e.g. $b << 1 give 0b101001100
  • >> SHIFT RIGHT - bitwise SHIFT RIGHT the left operand, right operand times e.g. $b >> 1 give 0b01010011

Logical Operators

Evaluate logical relations between operands.

Logical operators calculate a logical value - TRUE or FALSE, per the values of their operands.

  • and Logical AND operator - return TRUE if both the operands are true, otherwise FALSE
  • && Logical AND operator - return TRUE if both the operands are true, otherwise FALSE
  • or Logical OR operator - return TRUE if either one of the operands is true, otherwise FALSE
  • || Logical OR operator - return TRUE if either one of the operands is true, otherwise FALSE
  • xor Logical XOR operator - return TRUE if one of the operands is true and the other is false, otherwise FALSE
  • not Logical NOT operator (unary operator)- return TRUE if the operand is false, otherwise FALSE
  • ! Logical NOT operator (unary operator)- return TRUE if the operand is false, otherwise FALSE

String Operators

Manipulate string scalar values.

  • . String concatenation operator - concatenate the left and right operands e.g. $a . $b gives "world hello"
  • x String repetition operator - return the left operand repeated the number of times specified by the right operator. E.g. $b x 3 gives "hellohellohello"

Miscellaneous Operators

  • .. The range operator - returns an array of values reflecting the sequential range beteen the two operands. For numeric operands, the values are incremented by 1 from the left operand to the right operand. For letters (lowercase or uppercase), the values are incremented in alphabetical order.

Follow these instructions and print the result after each step.

  • Assign scalar $a to a starting value of 5. Print value of $a .
  • Add 6 to the previous result. Print the new result.
  • Multiply the previous result by 2. Print the new result.
  • Autoincrement the previous result. Print the new result.
  • Substract 9 from the previous result. Print the new result.
  • Divide the previous result by 7. Print the new result.

Sphere Engine

Coding for Kids is an online interactive tutorial that teaches your kids how to code while playing!

Receive a 50% discount code by using the promo code:

Start now and play the first chapter for free, without signing up.

perl defined or assignment operator

perl defined or assignment operator

Perl Operators

A perl operator is a series of symbols used as syntax. An operator is a sort of function and its operands are arguments.

Operator Precedence

Perl precedence acts like BODMAS in Mathematics. Addition and Subtraction always comes after the Multiplication and Division.

For example,

Here, answer will be 2 with BODMAS rule. (6 / 3 = 2) will be calculated first, then the quotient 2 will be multiplied by the 5, followed by subtraction and addition.

Operator Precedence Table

Operator associativity.

The associativity of an operator helps you to decide whether to evaluate an equation from (left to right) or (right to left).

The order of operation is very important. Sometimes it is same from both the sides but sometimes it produces drastic difference.

The answer for this question is same in any order either from left or right.

3 ∗∗ 2 ∗∗ 3

The answer for this question will be (9 ∗∗ 3) from left and (3 ∗∗ 8) from right. Both the answers have a lot of difference.

Associativity Table

The arity of an operator can be defined as the number of operands on which it operates.

A nullary operator operates on zero operand, a unary operator operates on one operand, a binary operator operates on two operands and a listary operator operates on list of operands.

Arithmetic operators are usually left associative. Here, (3 + 3) evaluates first and then goes to the second (-) operator.

Operator fixity can be defined as its position relative to its operands.

Here, + operator appears in between the operands 3 and 2

Here, ! and - operator appears before the operands $a and 3.

Here, ++ operator appears after the operands $x.

The Effective Perler

Effective Perl Programming – write better, more idiomatic Perl

Set default values with the defined-or operator.

[ This is a mid-week bonus Item since it’s so short ]

Prior to Perl 5.10, you had to be a bit careful checking a Perl variable before you set a default value. An uninitialized value and a defined but false value both acted the same in the logical || short-circuit operator. The Perl idiom to set a default value looks like this:

That’s the binary-assignment equivalent of an expression where you type out the variable twice:

However, some of the false values might be perfectly valid and meaningful. If there are no rabbits in the hutch, you don’t want to replace that actual value, which just happens to be false, with the default:

The undef value, however, is actually the absence of value. It’s the absence of meaningful value. Replacing that with a default is reasonable:

To get around this, you don’t use the short-circuit operator. Instead, you can use the conditional operator, typing out the variable name three times:

You’ll mostly likely use this when you’re processing the command-line options or subroutine arguments:

That’s a bit messy, so Perl 5.10 introduces the defined-or operator, // . Instead of testing for truth, it tests for defined-ness. If its lefthand value is defined, even if it’s false (i.e. 0 , '0' , or the empty string), that’s what it returns, short-circuiting the righthand side. This works just fine, not replacing the 0 value that’s in $rabbits already:

You can now reduce this back to the binary-assignment idiom:

Now your subroutine paramter defaults look a bit neater:

This isn’t one of the Perl 5.10 features that you have to explicitly enable ( Item 2: Enable new Perl features when you need them ). As long as you are using Perl 5.10 or later it’s already available to you. However, you should still specify the Perl version ( Item 83. Limit your distributions to the right platforms. ).

4 thoughts on “Set default values with the defined-or operator.”

You mention that

To get around this, you don’t use the short-circuit operator. Instead, you can use the conditional operator, typing out the variable name three times: $value = defined $value ? $value : 'some default';

As long as you’re not using // , wouldn’t you write that rather

Yes, you could also use a postfix conditional.

Iosif, what would happen if $value was defined? The conditional brian displays handles setting the value either way; you would have to write an assignment first and then your check for definedness, resulting in more code and slightly less understandable at first sight.

In Iosif’s example, the variable keeps the value if already had if it is defined. In the example he quotes, I assigned the same value back to the same variable. At the end both do the same thing, but I was making a larger point. Even in his streamlined example, he has to type the variable name twice.

Comments are closed.

1. Variables and their Related Operators

Computer Hope

Perl 5 operators

The Perl programming language offers many powerful ways to operate on data. This page describes data operations in Perl 5, and how to use them.

  • Precedence And Associativity

Terms and List Operators (Leftward)

The arrow operator.

  • Auto-Increment-And-Auto-Decrement

Exponentiation

Symbolic unary operators, binding operators, multiplicative operators, additive operators, shift operators, named unary operators, relational operators, equality operators, smartmatch operator, bitwise and.

  • Bitwise Or And Exclusive Or

C-style Logical AND

  • C-style Logical OR

Logical Defined-Or

Range operators, conditional operator, assignment operators, comma operator, list operators (rightward), logical not, logical and.

  • Logical Or And Exclusive Or

C Operators Missing From Perl

Quote and quote-like operators.

  • Regexp Quote-like Operators
  • Quote-Like-Operators
  • Gory Details Of Parsing Quoted Constructs

I/O Operators

Constant folding.

  • itwise-String-Operators

Integer Arithmetic

  • Floating Point Arithmetic

Bigger Numbers

  • Perl Overview
  • Linux commands help

Operator Precedence and Associativity

Operator precedence and associativity work in Perl more or less like they do in mathematics.

"Operator precedence" means some operators are evaluated before others. For example, in 2 + 4 * 5 , the multiplication has higher precedence so 4 * 5 is evaluated first, yielding 2 + 20 == 22 and not 6 * 5 == 30 .

Operator associativity defines what happens if a sequence of the same operators is used one after another: whether the evaluator will evaluate the left operations first or the right. For example, in 8 - 4 - 2 , subtraction is left associative so Perl evaluates the expression left to right. 8 - 4 is evaluated first making the expression 4 - 2 == 2 and not 8 - 2 == 6 .

Perl operators have the following associativity and precedence, listed from highest precedence to lowest. Operators borrowed from C keep the same precedence relationship, even where C's precedence is slightly screwy. This makes learning Perl easier for C folks. With very few exceptions, these all operate on scalar values only, not array values.

In the following sections, these operators are covered in precedence order.

Many operators can be overloaded for objects.

A TERM has the highest precedence in Perl. They include variables, quote and quote-like operators, any expression in parentheses, and any function whose arguments are parenthesized. Actually, there aren't really functions in this sense, just list operators and unary operators behaving as functions because you put parentheses around the arguments. These are all documented in Perl Functions .

If any list operator ( print() , etc.) or any unary operator ( chdir() , etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, like a normal function call.

In the absence of parentheses, the precedence of list operators such as print , sort , or chmod is either very high or very low depending on whether you are looking at the left side or the right side of the operator. For example, in

the commas on the right of the sort are evaluated before the sort , but the commas on the left are evaluated after. In other words, list operators tend to gobble up all arguments that follow, and then act like a simple TERM with regard to the preceding expression. Be careful with parentheses:

Also, note that

probably doesn't do what you expect at first glance. The parentheses enclose the argument list for print that is evaluated (printing the result of $foo & 255 ). Then one is added to the return value of print (usually 1 ). The result is something like this:

To do what you meant properly, you must write:

See Named Unary Operators for more discussion of this.

Also, parsed as terms are the do {} and eval {} constructs, and subroutine and method calls, and the anonymous constructors [] and {} .

See also Quote and Quote-like Operators toward the end of this section, as well as I/O Operators .

" -> " is an infix dereference operator, as it is in C and C++. If the right side is either a [...] , {...} , or a (...) subscript, then the left side must be either a hard or symbolic reference to an array, a hash, or a subroutine respectively. Or technically speaking, a location capable of holding a hard reference, if it's an array or hash reference used for assignment.

Otherwise, the right side is a method name or a simple scalar variable containing either the method name or a subroutine reference, and the left side must be either an object (a blessed reference) or a class name (that is, a package name).

Auto-increment and Auto-decrement

" ++ " and " -- " work as in C. That is, if placed before a variable, they increment or decrement the variable by one before returning the value, and if placed after, increment or decrement after returning the value.

Note that as in C, Perl doesn't define when the variable is incremented or decremented. You know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior. Avoid statements like:

Perl will not guarantee what the result of the above statements is.

The auto-increment operator has a little extra builtin magic to it. If you increment a variable that is numeric, or has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern /^[a-zA-Z]*[0-9]*\z/ , the increment is done as a string, preserving each character within its range, with carry:

undef is always treated as numeric, and in particular is changed to 0 before incrementing (so that a post-increment of an undef value returns 0 rather than undef ).

The auto-decrement operator is not magical.

Binary " ** " is the exponentiation operator. Here, "binary" means that it operates on two values. It binds even more tightly than unary minus, so -2**4 is -(2**4) , not (-2)**4 . This is implemented using C's pow() function, which actually works on doubles internally.

Unary " ! " performs logical negation, that is, " not ".

Unary " - " performs arithmetic negation if the operand is numeric, including any string that looks like a number. If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned. One effect of these rules is that -bareword is equivalent to the string " -bareword ". If, however, the string begins with a non-alphabetic character (excluding " + " or " - "), Perl attempts to convert the string to a numeric and the arithmetic negation is performed. If the string cannot be cleanly converted to a numeric, Perl gives the warning "Argument "the string" isn't numeric in negation (-) at ...".

Unary " ~ " performs bitwise negation, that is, 1 's complement. For example, 0666 & ~027 is 0640 . See also Integer Arithmetic and Bitwise String Operators . Note that the width of the result is platform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64 bits wide on a 64-bit platform, so if you are expecting a certain bit width, remember to use the " & " operator masking off the excess bits.

When complementing strings, if all characters have ordinal values under 256, then their complements will, also. But if they do not, all characters will be in either 32- or 64-bit complements, depending on your architecture. So for example, ~"\x{3B1}" is "\x{FFFF_FC4E}" on 32-bit machines and "\x{FFFF_FFFF_FFFF_FC4E}" on 64-bit machines.

Unary " + " has no effect whatsoever, even on strings . It is useful syntactically for separating a function name from a parenthesized expression that would otherwise be interpreted as the complete list of function arguments. See examples above under Terms and List Operators (Leftward) .

Unary " \ " creates a reference to whatever follows it. Do not confuse this behavior with the behavior of backslash within a string, although both forms do convey the notion of protecting the next thing from interpolation.

Binary " =~ " binds a scalar expression to a pattern match. Certain operations search or modify the string $_ by default. This operator makes that kind of operation work on some other string. The right argument is a search pattern, substitution, or transliteration. The left argument is what is supposed to be searched, substituted, or transliterated instead of the default $_ . When used in scalar context, the return value generally indicates the success of the operation. The exceptions are substitution ( s/// ) and transliteration ( y/// ) with the /r (non-destructive) option, which cause the return value to be the result of the substitution. Behavior in list context depends on the particular operator. See Regexp Quote-Like Operators for details and perlretut for examples using these operators.

If the right argument is an expression rather than a search pattern, substitution, or transliteration, it's interpreted as a search pattern at run time. Note that this means that its contents will be interpolated twice, so

is not ok, as the regex engine will end up trying to compile the pattern \ , which it will consider a syntax error.

Binary " !~ " is like " =~ " except the return value is negated in the logical sense.

Binary " !~ " with a non-destructive substitution ( s///r ) or transliteration ( y///r ) is a syntax error.

Binary " * " multiplies two numbers.

Binary " / " divides two numbers.

Binary " % " is the modulo operator, which computes the division remainder of its first argument with respect to its second argument. Given integer operands $a and $b : If $b is positive, then $a % $b is $a minus the largest multiple of $b less than or equal to $a . If $b is negative, then $a % $b is $a minus the smallest multiple of $b that is not less than $a (that is, the result will be less than or equal to zero). If the operands $a and $b are floating point values and the absolute value of $b (that is abs($b) ) is less than (UV_MAX + 1) , only the integer portion of $a and $b will be used in the operation (Note: here UV_MAX means the maximum of the unsigned integer type). If the absolute value of the right operand (abs($b)) is greater than or equal to (UV_MAX + 1) , " % " computes the floating-point remainder $r in the equation ( $r = $a - $i*$b ) where $i is a certain integer that makes $r have the same sign as the right operand $b (not as the left operand $a like C function fmod() ) and the absolute value less than that of $b . Note that when use integer is in scope, " % " gives you direct access to the modulo operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster.

Binary " x " is the repetition operator. In scalar context or if the left operand is not enclosed in parentheses, it returns a string consisting of the left operand repeated the number of times specified by the right operand. In list context, if the left operand is enclosed in parentheses or is a list formed by qw/STRING/ , it repeats the list. If the right operand is zero or negative, it returns an empty string or an empty list, depending on the context.

Binary + returns the sum of two numbers.

Binary - returns the difference of two numbers.

Binary . concatenates two strings.

Binary << returns the value of its left argument shifted left by the number of bits specified by the right argument. Arguments should be integers. See also Integer Arithmetic .

Binary >> returns the value of its left argument shifted right by the number of bits specified by the right argument. Arguments should be integers. See also Integer Arithmetic .

Note that both << and >> in Perl are implemented directly using << and >> in C. If use integer (see Integer Arithmetic) is in force then signed C integers are used, else unsigned C integers are used. Either way, the implementation isn't going to generate results larger than the size of the integer type Perl was built with (32 bits or 64 bits).

The result of overflowing the range of the integers is undefined because it is undefined also in C. In other words, using 32-bit integers, 1 << 32 is undefined. Shifting by a negative number of bits is also undefined.

If you get tired of being subject to your platform's native integers, the use bigint pragma neatly sidesteps the issue altogether:

but, because * is higher precedence than named operators:

Regarding precedence, the filetest operators, like -f , -M , etc. are treated like named unary operators, but they don't follow this functional parenthesis rule. That means, for example, that -f($file).".bak" is equivalent to -f "$file.bak" .

Perl operators that return true or false generally return values that can be safely used as numbers. For example, the relational operators in this section and the equality operators in the next one return 1 for true and a special version of the defined empty string, "" , which counts as a zero but is exempt from warnings about improper numeric conversions, just as " 0 but true " is.

Binary " < " returns true if the left argument is numerically less than the right argument.

Binary " > " returns true if the left argument is numerically greater than the right argument.

Binary " <= " returns true if the left argument is numerically less than or equal to the right argument.

Binary " >= " returns true if the left argument is numerically greater than or equal to the right argument.

Binary " lt " returns true if the left argument is stringwise less than the right argument.

Binary " gt " returns true if the left argument is stringwise greater than the right argument.

Binary " le " returns true if the left argument is stringwise less than or equal to the right argument.

Binary " ge " returns true if the left argument is stringwise greater than or equal to the right argument.

Binary " == " returns true if the left argument is numerically equal to the right argument.

Binary " != " returns true if the left argument is numerically not equal to the right argument.

Binary " <=> " returns -1 , 0 , or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. If your platform supports NaNs (not-a-numbers) as numeric values, using them with " <=> " returns undef . NaN is not " < ", " == ", " > ", " <= " or " >= " anything (even NaN), so those 5 return false. NaN != NaN returns true, as does NaN != anything else. If your platform doesn't support NaNs then NaN is a string with numeric value 0.

Note that the bigint , bigrat , and bignum pragmas all support "NaN".

Binary " eq " returns true if the left argument is stringwise equal to the right argument.

Binary " ne " returns true if the left argument is stringwise not equal to the right argument.

Binary " cmp " returns -1 , 0 , or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.

Binary " ~~ " does a smartmatch between its arguments. Smart matching is described in the next section.

" lt ", " le ", " ge ", " gt " and " cmp " use the collation (sort) order specified by the current locale if a legacy use locale (but not use locale ' :not_characters ' ) is in effect. Do not mix these with Unicode, only with legacy binary encodings. The standard Unicode::Collate and Unicode::Collate::Locale modules offer much more powerful solutions to collation issues.

First available in Perl 5.10.1 (the 5.10.0 version behaved differently), binary ~~ does a "smartmatch" between its arguments. This is mostly used implicitly in the when construct described in Perl Syntax , although not all when clauses call the smartmatch operator. Unique among all Perl's operators, the smartmatch operator can recurse .

It is also unique in that all other Perl operators impose a context (usually string or numeric context) on their operands, autoconverting those operands to those imposed contexts. In contrast, smartmatch infers contexts from the actual types of its operands and uses that type information to select a suitable comparison mechanism.

The ~~ operator compares its operands "polymorphically", determining how to compare them according to their actual types (numeric, string, array, hash, etc.) Like the equality operators with which it shares the same precedence, ~~ returns 1 for true and "" for false. It is often best read aloud as "in", "inside of", or "is contained in", because the left operand is often looked for inside the right operand. That makes the order of the operands to the smartmatch operand often opposite that of the regular match operator. In other words, the "smaller" thing is usually placed in the left operand and the larger one in the right.

The behavior of a smartmatch depends on what type of things its arguments are, as determined by the following table. The first row of the table whose types apply determines the smartmatch behavior. Because what actually happens is mostly determined by the type of the second operand, the table is sorted on the right operand instead of on the left.

General smartmatch behavior

When right operand is an array, when right operand is a hash, when right operand is code.

  • Empty hashes or arrays match.
  • That is, each element smartmatches the element of the same index in the other array.
  • If a circular reference is found, fall back to referential equality.
  • Either an actual number, or a string that looks like one.

The smartmatch implicitly dereferences any non-blessed hash or array reference, so the HASH and ARRAY entries apply in those cases. For blessed references, the Object entries apply. Smartmatches involving hashes only consider hash keys, never hash values.

The "like" code entry is not always an exact rendition. For example, the smartmatch operator short-circuits whenever possible, but grep does not. Also, grep in scalar context returns the number of matches, but ~~ returns only true or false.

Unlike most operators, the smartmatch operator knows to treat undef specially:

Each operand is considered in a modified scalar context, the modification being that array and hash variables are passed by reference to the operator, which implicitly dereferences them. Both elements of each pair are the same:

Two arrays smartmatch if each element in the first array smartmatches (that is, is "in") the corresponding element in the second array, recursively.

Because the smartmatch operator recurses on nested arrays, this still reports that "red" is in the array.

If two arrays smartmatch each other, then they are deep copies of each others' values, as this example reports:

If you were to set $b[3] = 4 , then instead of reporting that "a and b are deep copies of each other", it now reports that "b smartmatches in a". That because the corresponding position in @a contains an array that (eventually) has a 4 in it.

Smartmatching one hash against another reports whether both contain the same keys, no more and no less. This could be used to see whether two records have the same field names, without caring what values those fields might have. For example:

or, if other non-required fields are allowed, use ARRAY ~~ HASH :

The smartmatch operator is often used as the implicit operator of a when clause. See the Perl Syntax section on "Switch Statements" .

Smartmatching of Objects

To avoid relying on an object's underlying representation, if the smartmatch's right operand is an object that doesn't overload ~~ , it raises the exception "Smartmatching a non-overloaded object breaks encapsulation". That's because one has no business digging around to see whether something is "in" an object. These are all illegal on objects without a ~~ overload:

However, you can change the way an object is smartmatched by overloading the ~~ operator. This is allowed to extend the usual smartmatch semantics. For objects that do have an ~~ overload, see the overload pragma .

Using an object as the left operand is allowed, although not very useful. Smartmatching rules take precedence over overloading, so even if the object in the left operand has smartmatch overloading, this is ignored. A left operand that is a non-overloaded object falls back on a string or numeric comparison of whatever the ref operator returns. That means that

does not invoke the overload method with X as an argument. Instead the above table is consulted as normal, and based on the type of X , overloading may or may not be invoked. For simple strings or numbers, in becomes equivalent to this:

Binary "&" returns its operands ANDed together bit by bit. See also Integer Arithmetic and Bitwise String Operators .

Note that "&" has lower priority than relational operators, so for example the parentheses are essential in a test like

Bitwise Or and Exclusive Or

Binary " | " returns its operands ORed together bit by bit. See also Integer Arithmetic and Bitwise String Operators .

Binary " ^ " returns its operands XORed together bit by bit. See also Integer Arithmetic and Bitwise String Operators .

Note that " | " and " ^ " have lower priority than relational operators, so for example the brackets are essential in a test like

Binary "&&" performs a short-circuit logical AND operation. That is, if the left operand is false, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it's evaluated.

C-style Logical Or

Binary " || " performs a short-circuit logical OR operation. That is, if the left operand is true, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it's evaluated.

Although it has no direct equivalent in C, Perl's // operator is related to its C-style or. In fact, it's the same as || , except that it tests the left side's definedness instead of its truth. Thus, EXPR1 // EXPR2 returns the value of EXPR1 if it's defined, otherwise, the value of EXPR2 is returned. ( EXPR1 is evaluated in scalar context, EXPR2 in the context of // itself). Usually, this is the same result as defined(EXPR1) ? EXPR1 : EXPR2 (except that the ternary-operator form can be used as a lvalue, while EXPR1 // EXPR2 cannot). This is very useful for providing default values for variables. If you actually want to test if at least one of $a and $b is defined, use defined($a // $b) .

The || , // and && operators return the last value evaluated (unlike C's || and && , which return 0 or 1 ). Thus, a reasonably portable way to find out the home directory might be:

In particular, this means you shouldn't use this for selecting between two aggregates for assignment:

As alternatives to && and || when used for control flow, Perl provides the and and or operators (see below). The short-circuit behavior is identical. The precedence of "and" and "or" is much lower, however, so you can safely use them after a list operator without the need for parentheses:

With the C-style operators that are written like this:

It would be even more readable to write that this way:

Using "or" for assignment is unlikely to do what you want; see below.

Binary " .. " is the range operator, which is really two different operators depending on the context. In list context, it returns a list of values counting (up by ones) from the left value to the right value. If the left value is greater than the right value then it returns the empty list. The range operator is useful for writing foreach (1..10) loops and for doing slice operations on arrays. In the current implementation, no temporary array is created when the range operator is used as the expression in foreach loops, but older versions of Perl might burn a lot of memory when you write something like this:

The range operator also works on strings, using the magical auto-increment, see below.

In scalar context, " .. " returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed , awk , and various editors. Each " .. " operator maintains its own boolean state, even across calls to a subroutine containing it. It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, AFTER which the range operator becomes false again. It doesn't become false till the next time the range operator is evaluated. It can test the right operand and become false on the same evaluation it became true (as in awk ), but it still returns true once. If you don't want it to test the right operand until the next evaluation, as in sed, use three dots (" ... ") instead of two. In all other regards, " ... " behaves like " .. " does.

The right operand is not evaluated while the operator is in the "false" state, and the left operand is not evaluated while the operator is in the "true" state. The precedence is a little lower than || and && . The value returned is either the empty string for false, or a sequence number (beginning with 1 ) for true. The sequence number is reset for each range encountered. The final sequence number in a range has the string " E0 " appended to it, which doesn't affect its numeric value, but gives you something to search for if you want to exclude the endpoint. You can exclude the beginning point by waiting for the sequence number to be greater than 1.

If either operand of scalar " .. " is a constant expression, that operand is considered true if it's equal ( == ) to the current input line number (the $. variable).

To be pedantic, the comparison is actually int(EXPR) == int(EXPR) , but that is only an issue if you use a floating point expression; when implicitly using $ . as described in the previous paragraph, the comparison is int(EXPR) == int($.) which is only an issue when $. is set to a floating point value and you are not reading from a file. Furthermore, "span" .. "spat" or 2.18 .. 3.14 will not do what you want in scalar context because each of the operands are evaluated using their integer representation.

As a scalar operator:

Here's a simple example to illustrate the difference between the two range operators:

This program prints only the line containing " Bar ". If the range operator is changed to ... , it also prints the " Baz " line.

And now examples as a list operator:

The range operator (in list context) makes use of the magical auto-increment algorithm if the operands are strings. You can say

to get all normal letters of the English alphabet, or

to get a hexadecimal digit, or

to get dates with leading zeros.

If the final value specified is not in the sequence that the magical increment would produce, the sequence goes until the next value would be longer than the final value specified.

If the initial value specified isn't part of a magical increment sequence (that is, a non-empty string matching /^[a-zA-Z]*[0-9]*\z/ ), only the initial value will be returned. So the following only returns an alpha:

To get the 25 traditional lowercase Greek letters, including both sigmas, you could use this instead:

However, because there are other lowercase Greek characters than those, to match lowercase Greek characters in a regular expression , you would use the pattern /(?:(?=\p{Greek})\p{Lower})+/ .

Because each operand is evaluated in integer form, 2.18 .. 3.14 returns two elements in list context.

Ternary " ?: " is the conditional operator, as in C. It works much like an if-then-else. If the argument before the ? is true, the argument before the : is returned, otherwise the argument after the : is returned. For example:

Scalar or list context propagates downward into the 2nd or 3rd argument, whichever is selected.

The operator may be assigned to if both the 2nd and 3rd arguments are legal lvalues (meaning you can assign to them):

Because this operator produces an assignable result, using assignments without parentheses gets you in trouble. For example, this:

Really means this:

Rather than this:

That should probably be written as:

" = " is the ordinary assignment operator.

Assignment operators work as in C. That is,

is equivalent to

although without duplicating any side effects that dereferencing the lvalue might trigger, such as from tie() . Other assignment operators work similarly. The following are recognized:

Although these are grouped by family, they all have the precedence of assignment.

Unlike in C, the scalar assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to. This is useful for modifying a copy of something, like this:

Although as of 5.14, that can be also be accomplished this way:

Similarly, a list assignment in list context produces the list of lvalues assigned to, and a list assignment in scalar context returns the number of elements produced by the expression on the right side of the assignment.

Binary " , " is the comma operator. In scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. This is like C's comma operator.

In list context, it's the list argument separator, and inserts both its arguments into the list. These arguments are also evaluated from left to right.

The => operator is a synonym for the comma except that it causes a word on its left to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores. This includes operands that might otherwise be interpreted as operators, constants, single number v-strings or function calls. If in doubt about this behavior, the left operand can be quoted explicitly.

Otherwise, the => operator behaves exactly as the comma operator or list argument separator, according to context.

For example:

is equivalent to:

The => operator is helpful in documenting the correspondence between keys and values in hashes, and other paired elements in lists.

The special quoting behavior ignores precedence, and hence may apply to part of the left operand:

That example prints something like " 1314363215shiftbbb ", because the => implicitly quotes the shift immediately on its left, ignoring the fact that time.shift is the entire left operand.

On the right side of a list operator, the comma has very low precedence, such that it controls all comma-separated expressions found there. The only operators with lower precedence are the logical operators "and", "or", and "not", which may be used to evaluate calls to list operators without the need for parentheses:

However, some people find that code harder to read than writing it with parentheses:

in which case you might as well use the more customary " || " operator:

Unary " not " returns the logical negation of the expression to its right. It's the equivalent of " ! " except for the very low precedence.

Binary " and " returns the logical conjunction of the two surrounding expressions. It's equivalent to && except for the very low precedence. This means that it short-circuits: the right expression is evaluated only if the left expression is true.

Logical Or and Exclusive Or

Binary " or " returns the logical disjunction of the two surrounding expressions. It's equivalent to || except for the very low precedence. This makes it useful for control flow:

This means that it short-circuits: the right expression is evaluated only if the left expression is false. Due to its precedence, you must be careful to avoid using it as replacement for the || operator. It usually works out better for flow control than in assignments:

However, when it's a list-context assignment and you're trying to use || for control flow, you probably need " or " so that the assignment takes higher precedence.

Then again, you could always use parentheses.

Binary xor returns the exclusive-OR of the two surrounding expressions. It cannot short-circuit (of course).

There is no low precedence operator for defined-OR .

Here is what C has that Perl doesn't:

  • unary & : Address-of operator. But see the " \ " operator for taking a reference.
  • unary * : Dereference-address operator. Perl's prefix dereferencing operators are typed: $ , @ , % , and & .
  • (TYPE) : Type-casting operator.

While we usually think of quotes as literal values, in Perl they function as operators, providing various kinds of interpolating and pattern matching capabilities. Perl provides customary quote characters for these behaviors, but also provides a way for you to choose your quote character for any of them. In the following table, a {} represents any pair of delimiters you choose.

In the table above, * indicates "unless the delimiter is '' ." (two consecutive single quotes).

Non-bracketing delimiters use the same character fore and aft, but the four sorts of ASCII brackets (round, angle, square, curly) all nest, which means that

is the same as

Note, however, that this does not always work for quoting Perl code:

is a syntax error. The Text::Balanced module (standard as of v5.8, and from CPAN before then) can do this properly.

There can be whitespace between the operator and the quoting characters, except when # is used as the quoting character. q#foo# is parsed as the string foo , while q #foo# is the operator q followed by a comment . Its argument will be taken from the next line. This allows you to write:

The following escape sequences are available in constructs that interpolate, and in transliterations:

The "Notes" above are as follows:

Only hexadecimal digits are valid between the braces. If an invalid character is encountered, a warning will be issued and the invalid character and all subsequent characters (valid or invalid) in the braces will be discarded.

If there are no valid digits between the braces, the generated character is the NULL character ( \x{00} ). However, an explicit empty brace ( \x{} ) will not cause a warning (currently).

Only hexadecimal digits are valid following \x . When \x is followed by fewer than two valid digits, any valid digits will be zero-padded. This means that \x7 will be interpreted as \x07 , and a lone <\x> will be interpreted as \x00 . Except at the end of a string, having fewer than two valid digits results in a warning. Note that although the warning says the illegal character is ignored, it is only ignored as part of the escape and still used as the subsequent character in the string. For example:

  • The result is the Unicode character or character sequence given by name. See charnames .
  • \N{U+hexadecimal number} means the Unicode character whose Unicode code point is hexadecimal number.

In other words, it's the character whose code point has had 64 xor'd with its uppercase. \c? is DELETE because ord ("?") ^ 64 is 127 , and \c@ is NULL because the ord of " @ " is 64 , so xor'ing 64 itself produces 0 .

Also, \c\X yields chr(28) . " X " for any X , but cannot come at the end of a string, because the backslash would be parsed as escaping the end quote.

On ASCII platforms, the resulting characters from the list above are the complete set of ASCII controls. This isn't the case on EBCDIC platforms.

Use of any other character following the " c " besides those listed above is discouraged, and some are deprecated with the intention of removing those in a later Perl version. What happens for any of these other characters currently though, is that the value is derived by xor'ing with the seventh bit, which is 64.

To get platform independent controls, you can use \N{...} .

If a character that isn't an octal digit is encountered, a warning is raised, and the value is based on the octal digits before it, discarding it and all following characters up to the closing brace. It is a fatal error if there are no octal digits at all.

Some contexts allow 2 or even 1 digit, but any usage without exactly three digits, the first being a zero, may give unintended results. For example, in a regular expression it may be confused with a backreference; see Octal escapes in perlrebackslash . Starting in Perl 5.14, you may use \o{} instead, which avoids all these problems. Otherwise, it is best to use this construct only for ordinals \077 and below, remembering to pad to the left with zeros to make three digits. For larger ordinals, either use \o{} , or convert to something else, such as to hex and use \x{} instead.

Having fewer than 3 digits may lead to a misleading warning message that says that what follows is ignored. For example, " \128 " in the ASCII character set is equivalent to the two characters " \n8 " , but the warning "Illegal octal digit '8' ignored" will be thrown. If " \n8 " is what you want, you can avoid this warning by padding your octal number with 0 's: " \0128 ".

There are a few exceptions to the above rule. \N{U+hex number} is always interpreted as a Unicode code point, so that \N{U+0050} is " P " even on EBCDIC platforms. And if use encoding is in effect, the number is considered to be in that encoding, and is translated from that into the platform's native encoding if there is a corresponding native character; otherwise to Unicode.

Unlike C and other languages, Perl has no \ v escape sequence for the vertical tab ( VT , which is 11 in both ASCII and EBCDIC), but you may use \ck or \x0b . ( \v does have meaning in regular expression patterns in Perl.

The following escape sequences are available in constructs that interpolate, but not in transliterations.

\L , \U , \F , and \Q can stack, in which case you need one \E for each. For example:

If use locale is in effect (but not use locale ':not_characters' ), the case map used by \l , \L , \u , and \U is taken from the current locale. If Unicode (for example, \N{} or code points of 0x100 or beyond) is used, the case map used by \l , \L , \u , and \U is as defined by Unicode. That means that case-mapping a single character can sometimes produce several characters. Under use locale , \F produces the same results as \L .

All systems use the virtual " \n " to represent a line terminator, called a " newline ". There is no such thing as an unvarying, physical newline character. It is only an illusion that the operating system, device drivers, C libraries, and Perl all conspire to preserve. Not all systems read " \r " as ASCII CR and " \n " as ASCII LF . For example, on the ancient Macs (pre-MacOS X) of yesteryear, these used to be reversed, and on systems without line terminator, printing " \n " might emit no actual data. In general, use " \n " when you mean a "newline" for your system, but use the literal ASCII when you need an exact character. For example, most networking protocols expect and prefer a CR+LF (" \015\012 " or " \cM\cJ " ) for line terminators, and although they often accept " \012 ", they seldom tolerate " \015 ". If you get in the habit of using " \n " for networking, you may be burned some day.

For constructs that do interpolate, variables beginning with " $ " or " @ " are interpolated. Subscripted variables such as $a[3] or $href->{key}[0] are also interpolated, as are array and hash slices. But method calls such as $obj->meth are not.

Interpolating an array or slice interpolates the elements in order, separated by the value of $" , so is equivalent to interpolating join $", @array . "Punctuation" arrays such as @* are usually interpolated only if the name is enclosed in braces @{*} , but the arrays @_ , @+ , and @- are interpolated even without braces.

For double-quoted strings, the quoting from \Q is applied after interpolation and escapes are processed.

For the pattern of regex operators ( qr// , m// and s/// ), the quoting from \Q is applied after interpolation is processed, but before escapes are processed. This allows the pattern to match literally (except for $ and @ ). For example, the following matches:

Because $ or @ trigger interpolation, you'll need to use something like /\Quser\E\@\Qhost/ to match them literally.

Patterns are subject to an additional level of interpretation as a regular expression. This is done as a second pass, after variables are interpolated, so that regular expressions may be incorporated into the pattern from the variables. If this is not what you want, use \Q to interpolate a variable literally.

Apart from the behavior described above, Perl does not expand multiple levels of interpolation. In particular, contrary to the expectations of shell programmers, backquotes do NOT interpolate within double quotes, nor do single quotes impede evaluation of variables when used within double quotes.

Regexp Quote-Like Operators

Here are the quote-like operators that apply to pattern matching and related activities.

This operator quotes (and possibly compiles) its STRING as a regular expression. STRING is interpolated the same way as PATTERN in m/PATTERN/ . If ' is used as the delimiter, no interpolation is done. Returns a Perl value which may be used instead of the corresponding /STRING/msixpodual expression. The returned value is a normalized version of the original pattern. It magically differs from a string containing the same characters: ref(qr/x/) returns " Regexp "; however, dereferencing it is not well defined (you currently get the normalized version of the original pattern, but this may change).

For example,

The result may be used as a subpattern in a match:

Since Perl may compile the pattern at the moment of execution of the qr() operator, using qr() may have speed advantages in some situations, notably if the result of qr() is used standalone:

Precompilation of the pattern into an internal representation at the moment of qr() avoids a need to recompile the pattern every time a match /$pat/ is attempted. Perl has other internal optimizations, but none would be triggered in the above example if we did not use qr() operator.

Options (specified by the following modifiers) are:

If a precompiled pattern is embedded in a larger pattern then the effect of " msixpluad " will be propagated appropriately. The effect the " o " modifier has is not propagated, being restricted to those patterns explicitly using it.

The last four modifiers listed above, added in Perl 5.14, control the character set semantics, but /a is the only one you are likely to want to specify explicitly; the other three are selected automatically by various pragmas.

See perlre for additional information on valid syntax for STRING , and for a detailed look at the semantics of regular expressions. In particular, all modifiers except the largely obsolete /o are further explained in Modifiers in perlre. /o is described in the next section.

Searches a string for a pattern match, and in scalar context returns true if it succeeds, false if it fails. If no string is specified via the =~ or !~ operator, the $_ string is searched. The string specified with =~ need not be an lvalue; it may be the result of an expression evaluation, but remember the =~ binds rather tightly. See also perlre .

Options are as described in qr// above; in addition, the following match process modifiers are available:

If " / " is the delimiter then the initial m is optional. With the m , you can use any pair of non-whitespace (ASCII) characters as delimiters. This is particularly useful for matching path names that contain " / ", to avoid LTS (leaning toothpick syndrome). If " ? " is the delimiter, then a match-only-once rule applies, described in m?PATTERN? below. If ' is the delimiter, no interpolation is performed on the PATTERN . When using a character valid in an identifier, whitespace is required after the m .

PATTERN may contain variables, which will be interpolated every time the pattern search is evaluated, except for when the delimiter is a single quote. Note that $( , $) , and $| are not interpolated because they look like end-of-string tests. Perl will not recompile the pattern unless an interpolated variable that it contains changes. You can force Perl to skip the test and never recompile by adding a /o (which stands for "once") after the trailing delimiter. Once upon a time (see what we did there?), Perl would recompile regular expressions unnecessarily, and this modifier was useful to tell it not to do so, in the interests of speed. But now, the only reasons to use /o are either:

• The variables are thousands of characters long and you know that they don't change, and you need to wring out the last little bit of speed by having Perl skip testing for that. There is a maintenance penalty for doing this, as mentioning /o constitutes a promise you won't change the variables in the pattern. If you do change them, Perl won't even notice.

• you want the pattern to use the initial values of the variables regardless of whether they change or not. But there are saner ways of accomplishing this than using /o .

• If the pattern contains embedded code, such as:

...then perl will recompile each time, even though the pattern string hasn't changed, to ensure that the current value of $x is seen each time. Use /o if you want to avoid this.

The bottom line is that using /o is almost never a good idea.

If the PATTERN evaluates to the empty string, the last successfully matched regular expression is used instead. In this case, only the g and c flags on the empty pattern are honored; the other flags are taken from the original pattern. If no match has previously succeeded, this will (silently) act instead as a genuine empty pattern (which always match).

Note that it's possible to confuse Perl into thinking // (the empty regex) is really // (the defined-or operator). Perl is usually pretty good about this, but some pathological cases might trigger this, such as $a/// (is that ($a) / (//) or $a // /? ) and print $fh // ( print $fh(// or print($fh // ?). In all these examples, Perl will assume you meant defined-or . If you meant the empty regex, use parentheses or spaces to disambiguate, or even prefix the empty regex with an m (so // becomes m// ).

If the /g option is not used, m// in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, that is, ( $1 , $2 , $3 ...) (Note that here $1 etc. are also set). When there are no parentheses in the pattern, the return value is the list (1) for success. With or without parentheses, an empty list is returned upon failure.

This last example splits $foo into the first two words and the remainder of the line, and assigns those three fields to $F1 , $F2 , and $Etc . The conditional is true if any variables were assigned; that is, if the pattern matched.

The /g modifier specifies global pattern matching; that is, matching as many times as possible in the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.

In scalar context, each execution of m//g finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the pos() function. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the /c modifier (for example, m//gc ). Modifying the target string also resets the search position.

You can intermix m//g matches with m/\G.../g , where \G is a zero-width assertion that matches the exact position where the previous m//g , if any, left off. Without the /g modifier, the \G assertion still anchors at pos() as it was at the start of the operation (see pos ), but the match is of course only attempted once. Using \G without /g on a target string that has not previously had a /g match applied to it is the same as using the \A assertion to match the beginning of the string. Note also that, currently, \G is only properly supported when anchored at the very beginning of the pattern.

Here's another way to check for sentences in a paragraph:

Here's how to use m//gc with \G :

The last example should print:

Notice that the final match matched q instead of p , which a match without the \ G anchor would have done. Also, note that the final match did not update pos . pos is only updated on a / g match. If the final match did indeed match p , it's a good bet you're running a very old (pre-5.6.0) version of Perl.

A useful idiom for lex -like scanners is /\G.../gc . You can combine several regexps like this to process a string part-by-part, doing different actions depending on which regexp matched. Each regexp tries to match where the previous one leaves off.

Here is the output (split into several lines):

This is like the m/PATTERN/ search, except that it matches only once between calls to the reset() operator. This is a useful optimization when you want to see only the first occurrence of something in each file of a set of files, for instance. Only m?? patterns local to the current package are reset.

Another example switched the first " latin1 " encoding it finds to " utf8 " in a pod file:

The match-once behavior is controlled by the match delimiter being ? ; with any other delimiter this is the normal m// operator.

For historical reasons, the leading m in m?PATTERN? is optional, but the resulting ?PATTERN? syntax is deprecated, will warn on usage and might be removed from a future stable release of Perl (without further notice!).

Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise, it returns false (specifically, the empty string).

If the /r (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when /r is used. The copy is always a plain string, even if the input is an object or a tied variable.

If no string is specified via the =~ or !~ operator, the $_ variable is searched and modified. Unless the /r option is used, the string specified must be a scalar variable, an array element, a hash element, or an assignment to one of those; that is, some sort of scalar lvalue.

If the delimiter chosen is a single quote, no interpolation is done on either the PATTERN or the REPLACEMENT . Otherwise, if the PATTERN contains a $ that looks like a variable rather than an end-of-string test, the variable will be interpolated into the pattern at runtime. If you want the pattern compiled only once the first time the variable is interpolated, use the /o option. If the pattern evaluates to the empty string, the last successfully executed regular expression is used instead. See perlre for further explanation on these.

Options are as with m// with the addition of the following replacement specific options:

Any non-whitespace delimiter may replace the slashes. Add space after the s when using a character allowed in identifiers. If single quotes are used, no interpretation is done on the replacement string (the /e modifier overrides this, however). Note that Perl treats backticks as normal delimiters; the replacement text is not evaluated as a command. If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own pair of quotes, which may or may not be bracketing quotes, for example, s(foo)(bar) or s/bar/ . A /e causes the replacement portion to be treated as a full-fledged Perl expression and evaluated right then and there. It is, however, syntax checked at compile-time. A second e modifier causes the replacement portion to be evaled before being run as a Perl expression.

Note the use of $ instead of \ in the last example. Unlike sed , we use the \<digit> form in only the left side. Anywhere else it's $<digit> .

Occasionally, you can't use only a /g to get all the changes to occur you might want. Here are two common cases:

Quote-Like Operators

A single-quoted, literal string. A backslash represents a backslash unless followed by the delimiter or another backslash, in which case the delimiter or backslash is interpolated.

A double-quoted, interpolated string.

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards , pipes , and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected. In scalar context, it comes back as a single (potentially multi-line) string, or undef if the command failed. In list context, returns a list of lines (however you've defined lines with $/ or $INPUT_RECORD_SEPARATOR ), or an empty list if the command failed.

Because backticks do not affect standard error, use shell file descriptor syntax (assuming the shell supports this) if you care to address this. To capture a command's STDERR and STDOUT together:

To capture a command's STDOUT but discard its STDERR:

To capture a command's STDERR but discard its STDOUT (ordering is important here):

To exchange a command's STDOUT and STDERR to capture the STDERR but leave its STDOUT to come out the old STDERR:

To read both a command's STDOUT and its STDERR separately, it's easiest to redirect them separately to files, and then read from those files when the program is done:

The STDIN filehandle used by the command is inherited from Perl's STDIN. For example:

prints the sorted contents of the file named "stuff".

Using single-quote as a delimiter protects the command from Perl's double quote interpolation, passing it on to the shell instead:

How that string gets evaluated is entirely subject to the command interpreter on your system. On most platforms, you have to protect shell metacharacters if you want them treated literally. This is in practice difficult to do, as it's unclear how to escape which characters.

On some platforms (notably DOS -like ones), the shell may not be capable of dealing with multiline commands, so putting newlines in the string may not get you what you want. You can evaluate multiple commands in a single line by separating them with the command separator character, if your shell supports that (for example, " ; " on many Unix shells and & on the Windows NT cmd shell).

Perl attempts to flush all files opened for output before starting the child process , but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ( $AUTOFLUSH in English) or call the autoflush() method of IO::Handle on any open handles.

Beware that some command shells may place restrictions on the length of the command line. You must ensure your strings don't exceed this limit after any necessary interpolations. See the platform-specific release notes for more details about your particular environment.

Using this operator can lead to programs that are difficult to port, because the shell commands called vary between systems, and may in fact not be present at all. As one example, the type command under the POSIX shell is very different from the type command under DOS. That doesn't mean go out of your way to avoid backticks when they're the right way to get something done. Perl was made to be a glue language, and one of the things it glues together is commands. Understand what you're getting yourself into.

See I/O Operators for more discussion.

Evaluates to a list of the words extracted out of STRING , using embedded whitespace as the word delimiters. It can be understood as being roughly equivalent to:

the differences being that it generates a real list at compile time, and in scalar context it returns the last element in the list. So this expression:

A common mistake is to try to separate the words with comma or putting comments into a multi-line qw-string. For this reason, the use warnings pragma and the -w switch (that is, the $^W variable) produces warnings if the STRING contains the " , " or the " # " character.

Transliterates all occurrences of the characters found in the search list with the corresponding character in the replacement list. It returns the number of characters replaced or deleted. If no string is specified via the =~ or !~ operator, the $_ string is transliterated.

If the /r (non-destructive) option is present, a new copy of the string is made and its characters transliterated, and this copy is returned no matter whether it was modified or not: the original string is always left unchanged. The new copy is always a plain string, even if the input string is an object or a tied variable.

Unless the /r option is used, the string specified with =~ must be a scalar variable, an array element, a hash element, or an assignment to one of those; in other words, an lvalue.

A character range may be specified with a hyphen, so tr/A-J/0-9/ does the same replacement as tr/ACEGIBDFHJ/0246813579/. For sed devotees, y is provided as a synonym for tr . If the SEARCHLIST is delimited by bracketing quotes, the REPLACEMENTLIST has its own pair of quotes, which may or may not be bracketing quotes; for example, tr[aeiouy][yuoiea] or tr(+\-*/)/ABCD/ .

Note that tr does not do regular expression character classes such as \d or \pL . The tr operator is not equivalent to the tr utility. To map strings between lower/upper cases, see lc and uc , and in general consider using the s operator if you need regular expressions. The \U , \u , \L , and \l string-interpolation escapes on the right side of a substitution operator performs correct case-mappings, but tr[a-z][A-Z] will not (except sometimes on legacy 7-bit data).

Note also that the whole range idea is rather unportable between character sets, and even within character sets they may cause results you probably didn't expect. A sound principle is to use only ranges that begin from and end at either alphabets of equal case ( a-e , A-E ), or digits ( 0-4 ). Anything else is unsafe. If in doubt, spell out the character sets in full.

If the /c modifier is specified, the SEARCHLIST character set is complemented. If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted. Note that this is slightly more flexible than the behavior of some tr programs, which delete anything they find in the SEARCHLIST , period. If the /s modifier is specified, sequences of characters that were transliterated to the same character are squashed down to a single instance of the character.

If the /d modifier is used, the REPLACEMENTLIST is always interpreted exactly as specified. Otherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST , the final character is replicated till it is long enough. If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated. This latter is useful for counting characters in a class or for squashing character sequences in a class.

If multiple transliterations are given for a character, only the first one is used:

will transliterate any A to X .

Because the transliteration table is built at compile time, neither the SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote interpolation. That means that if you want to use variables, you must use an eval() :

A line-oriented form of quoting is based on the shell "here-document" syntax. Following a << you specify a string to terminate the quoted material, and all lines following the current line down to the terminating string are the value of the item.

The terminating string may be either an identifier (a word), or some quoted text. An unquoted identifier works like double quotes. There may not be a space between the << and the identifier, unless the identifier is explicitly quoted. If you put a space it will be treated as a null identifier, which is valid, and matches the first empty line. The terminating string must appear by itself (unquoted and with no surrounding whitespace) on the terminating line.

If the terminating string is quoted, the type of quotes used determine the treatment of the text.

Double quotes

Double quotes indicate that the text will be interpolated using the same rules as normal double quoted strings.

Single quotes

Single quotes indicate the text is to be treated literally with no interpolation of its content. This is similar to single quoted strings except that backslashes have no special meaning, with \\ being treated as two backslashes and not one as they would in every other quoting construct.

As in the shell, a backslashed bareword following the << means the same thing as a single-quoted string does:

This is the only form of quoting in Perl where there is no need to worry about escaping content, something of which code generators can and do make good use.

The content of the here doc is treated as it would be if the string were embedded in backticks. Thus the content is interpolated as though it were double quoted and then executed via the shell, with the results of the execution returned.

It is possible to stack multiple here-docs in a row:

Don't forget you have to put a semicolon on the end to finish the statement, as Perl doesn't know you're not going to try to do this:

To remove the line terminator from your here-docs, use chomp() .

If you want your here-docs to be indented with the rest of the code, you'll need to remove leading whitespace from each line manually:

If you use a here-doc within a delimited construct, such as in s///eg , the quoted material must still come on the line following the <<FOO marker, which means it may be inside the delimited construct:

It works this way as of Perl 5.18. Historically, it was inconsistent, and you would have to write

outside of string evals.

Additionally, quoting rules for the end-of-string identifier are unrelated to Perl's quoting rules. q() , qq() , and the like are not supported in place of '' and "" , and the only interpolation is for backslashing the quoting character:

Finally, quoted strings cannot span multiple lines. The general rule is that the identifier must be a string literal. Stick with that, and you'll be safe.

Gory details of parsing quoted constructs

When presented with something that might have different interpretations, Perl uses the DWIM (that's "Do What I Mean") principle to pick the most probable interpretation. This strategy is so successful that Perl programmers often do not suspect the ambivalence of what they write. But from time to time, Perl's notions differ substantially from what the author honestly meant.

This section hopes to clarify how Perl handles quoted constructs. Although the most common reason to learn this is to unravel labyrinthine regular expressions, because the initial steps of parsing are the same for all quoting operators, they are all discussed together.

The most important Perl parsing rule is the first one discussed below: when processing a quoted construct, Perl first finds the end of that construct, then interprets its contents. If you understand this rule, you may skip the rest of this section on the first reading. The other rules are likely to contradict the user's expectations much less frequently than this first one.

Some passes discussed below are performed concurrently, but because their results are the same, we consider them individually. For different quoting constructs, Perl performs different numbers of passes, from one to four, but these passes are always performed in the same order.

Finding the end

The first pass is finding the end of the quoted construct, where the information about the delimiters is used in parsing. During this search, text between the starting and ending delimiters is copied to a safe location. The text copied gets delimiter-independent.

If the construct is a here-doc, the ending delimiter is a line with a terminating string as the content. Therefore <<EOF is terminated by EOF immediately followed by " \n " and starting from the first column of the terminating line. When searching for the terminating line of a here-doc, nothing is skipped. In other words, lines after the here-doc syntax are compared with the terminating string line by line.

For the constructs except here-docs, single characters are used as starting and ending delimiters. If the starting delimiter is an opening punctuation (that is ( , [ , { , or < ), the ending delimiter is the corresponding closing punctuation (that is ) , ] , } , or > ). If the starting delimiter is an unpaired character like / or a closing punctuation, the ending delimiter is same as the starting delimiter. Therefore a / terminates a qq// construct, while a ] terminates qq[] and qq]] constructs.

When searching for single-character delimiters, escaped delimiters and \\ are skipped. For example, while searching for terminating / , combinations of \\ and \/ are skipped. If the delimiters are bracketing, nested pairs are also skipped. For example, while searching for closing ] paired with the opening [ , combinations of \\ , \] , and \[ are all skipped, and nested [ and ] are skipped as well. However, when backslashes are used as the delimiters (like qq\\ and tr\\\ ), nothing is skipped. During the search for the end, backslashes that escape delimiters or other backslashes are removed (exactly speaking, they are not copied to the safe location).

For constructs with three-part delimiters ( s/// , y/// , and tr/// ), the search is repeated once more. If the first delimiter is not an opening punctuation, three delimiters must be same such as s!!! and tr))) , in which case the second delimiter terminates the left part and starts the right part at once. If the left part is delimited by bracketing punctuation (that is () , [] , {} , or <> ), the right part needs another pair of delimiters such as s(){} and tr[]// . In these cases, whitespace and comments are allowed between both parts, though the comment must follow at least one whitespace character; otherwise a character expected as the start of the comment may be regarded as the starting delimiter of the right part.

During this search no attention is paid to the semantics of the construct. Thus:

do not form legal quoted expressions. The quoted part ends on the first " and / , and the rest happens to be a syntax error. Because the slash that terminated m// was followed by a SPACE , the example above is not m//x , but rather m// with no /x modifier. So the embedded # is interpreted as a literal # .

Also, no attention is paid to \c\ (multichar control char syntax) during this search. Thus the second \ in qq/\c\/ is interpreted as a part of \/ , and the following / is not recognized as a delimiter. Instead, use \034 or \x1c at the end of quoted constructs.

Interpolation

The next step is interpolation in the text obtained, which is now delimiter-independent. There are multiple cases:

No interpolation is performed. Note that the combination \\ is left intact since escaped delimiters are not available for here-docs.

No interpolation is performed at this stage. Any backslashed sequences including \\ are treated at the stage to parsing regular expressions.

The only interpolation is removal of \ from pairs of \\ . Therefore - in tr''' and y''' is treated literally as a hyphen and no character range is available. \1 in the replacement of s''' does not work as $1 .

No variable interpolation occurs. String modifying combinations for case and quoting such as \Q , \U , and \E are not recognized. The other escape sequences such as \200 and \t and backslashed characters such as \\ and \- are converted to appropriate literals. The character - is treated specially and therefore \- is treated as a literal - .

\Q , \U , \u , \L , \l , \F (possibly paired with \E ) are converted to corresponding Perl constructs. Thus, " $foo\Qbaz$bar " is converted to $foo. (quotemeta("baz" . $bar)) internally. The other escape sequences such as \200 and \t and backslashed characters such as \\ and \- are replaced with appropriate expansions.

Let it be stressed that whatever falls between \Q and \E is interpolated in the usual way. Something like " \Q\\E " has no \E inside. Instead, it has \Q , \\ , and E , so the result is the same as for " \\\\E ". As a general rule, backslashes between \Q and \E may lead to counterintuitive results. So, " \Q\t\E " is converted to quotemeta(" \t "), which is the same as " \\\t " (since Tab is not alphanumeric). Note also that:

may be closer to the conjectural intention of the writer of "\Q\t\E" .

Interpolated scalars and arrays are converted internally to the join and . catenation operations. Thus, "$foo XXX '@arr'" becomes:

All operations above are performed simultaneously, left to right.

Because the result of "\Q STRING \E" has all metacharacters quoted, there is no way to insert a literal $ or @ inside a \Q\E pair. If protected by \ , $ will be quoted to become "\\\$" ; if not, it's interpreted as the start of an interpolated scalar.

Note also that the interpolation code needs to decide on where the interpolated scalar ends. For instance, whether "a $b -> {c}" really means:

Most of the time, the longest possible text that does not include spaces between components and which contains matching braces or brackets. Because the outcome may be determined by voting based on heuristic estimators, the result is not strictly predictable. Fortunately, it's usually correct for ambiguous cases.

Processing of \Q , \U , \u , \L , \l , \F and interpolation happens as with qq// constructs.

It is at this step that \1 is begrudgingly converted to $1 in the replacement text of s/// , to correct the incorrigible sed hackers who haven't picked up the saner idiom yet. A warning is emitted if the use warnings pragma or the -w command-line flag (that is, the $^W variable) was set.

Processing of \Q , \U , \u , \L , \l , \F , \E , and interpolation happens (almost) as with qq// constructs.

Processing of \N{...} is also done here, and compiled into an intermediate form for the regex compiler. This is because, as mentioned below, the regex compilation may be done at execution time, and \N{...} is a compile-time construct.

However, any other combinations of \ followed by a character are not substituted but only skipped, to parse them as regular expressions at the following step. As \c is skipped at this step, @ of \c@ in RE is possibly treated as an array symbol (for example @foo ), even though the same text in qq// gives interpolation of \c@ .

Code blocks such as (?{BLOCK}) are handled by temporarily passing control back to the perl parser, in a similar way that an interpolated array subscript expression such as "foo$array[1+f("[xyz")]bar" would be.

Moreover, inside (?{BLOCK}) , (?# comment ) , and a # -comment in a //x regular expression, no processing is performed whatsoever. This is the first step at which the presence of the //x modifier is relevant.

Interpolation in patterns has several quirks: $| , $( , $) , @+ and @- are not interpolated, and constructs $var[SOMETHING] are voted (by different estimators) to be either an array element or $var followed by an RE alternative. This is where the notation ${arr[$bar]} comes handy: /${arr[0-9]}/ is interpreted as array element -9 , not as a regular expression from the variable $arr followed by a digit, which would be the interpretation of /$arr[0-9]/ . Since voting among different estimators may occur, the result is not predictable.

The lack of processing of \\ creates specific restrictions on the post-processed text. If the delimiter is / , one cannot get the combination \/ into the result of this step. / will finish the regular expression, \/ will be stripped to / on the previous step, and \\/ will be left as is. Because / is equivalent to \/ inside a regular expression, this does not matter unless the @tdelimiter happens to be character special to the RE engine, such as in s*foo*bar* , m[foo] , or ?foo? ; or an alphanumeric char, as in:

In the RE above, which is intentionally obfuscated for illustration, the delimiter is m , the modifier is mx , and after delimiter-removal the RE is the same as for m/ ^ a \s* b /mx . There's more than one reason you're encouraged to restrict your delimiters to non-alphanumeric, non-whitespace choices.

Parsing regular expressions

Previous steps were performed during the compilation of Perl code, but this one happens at run time, although it may be optimized to be calculated at compile time if appropriate. After preprocessing described above, and possibly after evaluation if concatenation, joining, casing translation, or metaquoting are involved, the resulting string is passed to the RE engine for compilation.

Whatever happens in the RE engine might be better discussed in perlre , but for the sake of continuity, we shall do so here.

This is another step where the presence of the //x modifier is relevant. The RE engine scans the string from left to right and converts it to a finite automaton.

Backslashed characters are either replaced with corresponding literal strings (as with \{ ), or else they generate special nodes in the finite automaton (as with \b ). Characters special to the RE engine (such as | ) generate corresponding nodes or groups of nodes. (?#...) comments are ignored. All the rest is either converted to literal strings to match, or else is ignored (as is whitespace and # -style comments if //x is present).

Parsing of the bracketed character class construct, [...] , is rather different than the rule used for the rest of the pattern. The terminator of this construct is found using the same rules as for finding the terminator of a {} -delimited construct, the only exception being that ] immediately following [ is treated as though preceded by a backslash.

The terminator of runtime (?{...}) is found by temporarily switching control to the perl parser, which should stop at the point where the logically balancing terminating } is found.

It is possible to inspect both the string given to RE engine and the resulting finite automaton. See the arguments debug /debugcolor in the use re pragma, as well as Perl's -Dr command-line switch documented in Perl Overview .

Optimization of regular expressions

This step is listed for completeness only. Since it does not change semantics, details of this step are not documented and are subject to change without notice. This step is performed over the finite automaton that was generated during the previous pass.

It is at this stage that split() silently optimizes /^/ to mean /^/m .

There are several I/O operators about which to know.

A string enclosed by backticks ( ` ` , the grave accents) first undergoes double quote interpolation. It is then interpreted as an external command, and the output of that command is the value of the backtick string, like in a shell. In scalar context, a single string consisting of all output is returned. In list context, a list of values is returned, one per line of output. You can set $/ to use a different line terminator. The command is executed each time the pseudo-literal is evaluated. The status value of the command is returned in $? (see perlvar for the interpretation of $? ). Unlike in csh , no translation is done on the return data; newlines remain newlines. Unlike in any of the shells, single quotes do not hide variable names in the command from interpretation. To pass a literal dollar sign through to the shell you need to escape it with a backslash. The generalized form of backticks is qx// . Because backticks always undergo shell expansion as well, see perlsec for security concerns.

In scalar context, evaluating a filehandle in angle brackets yields the next line from that file (the newline, if any, included), or undef at end-of-file or on error. When $/ is set to undef (sometimes known as file-slurp mode) and the file is empty, it returns '' the first time, followed by undef subsequently.

Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a while statement (even if disguised as a for(;;) loop), the value is automatically assigned to the global variable $_ , destroying whatever was there previously. This may seem like an odd thing to you, but you'll use the construct in almost every Perl script you write. The $_ variable is not implicitly localized. You'll have to put a local $_; before the loop if you want that to happen.

The following lines are equivalent:

This also behaves similarly, but assigns to a lexical variable instead of to $_ :

In these loop constructs, the assigned value (whether assignment is automatic or explicit) is then tested to see whether it is defined. The defined test avoids problems where the line has a string value that would be treated as false by Perl; for example a "" or a "0" with no trailing newline. If you mean for such values to terminate the loop, they should be tested for explicitly:

In other boolean contexts, <FILEHANDLE> without an explicit defined test or comparison elicits a warning if the use warnings pragma or the -w command-line switch (the $^W variable) is in effect.

The filehandles STDIN, STDOUT, and STDERR are predefined. The filehandles stdin , stdout , and stderr also works except in packages, where they would be interpreted as local identifiers rather than global. Additional filehandles may be created with the open() function, among others.

If a <FILEHANDLE> is used in a context that is looking for a list, a list comprising all input lines is returned, one line per list element. It's easy to grow to a rather large data space this way, so use with care.

<FILEHANDLE> may also be spelled readline(*FILEHANDLE) . See readline .

The null filehandle <> is special: it can emulate the behavior of sed and awk , and any other Unix filter program that takes a list of file names, doing the same to each line of input from them all. Input from <> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <> is evaluated, the @ARGV array is checked, and if it's empty, $ARGV[0] is set to " - ", which when opened gives you standard input. The @ARGV array is then processed as a list of file names. The loop

is equivalent to the following Perl-like pseudo code:

except that it isn't so cumbersome to say, and will actually work. It really does shift the @ARGV array and put the current filename into the $ARGV variable. It also uses filehandle ARGV internally. <> is a synonym for <ARGV>, which is magical. The pseudo code above doesn't work because it treats <ARGV> as non-magical.

Since the null filehandle uses the two argument form of open it interprets special characters, so if you have a script like this:

and call it with perl dangerous.pl 'rm -rfv *|' , it actually opens a pipe, executes the rm command and reads rm 's output from that pipe. If you want all items in @ARGV to be interpreted as file names, you can use the module ARGV::readonly from CPAN.

You can modify @ARGV before the first <> as long as the array ends up containing the list of filen ames you want. Line numbers ( $. ) continue as though the input were one big happy file. See the example in eof for how to reset line numbers on each file.

To set @ARGV to your list of files, go right ahead. This sets @ARGV to all plain text files if no @ARGV was given:

You can even set them to pipe commands. For example, this automatically filters compressed arguments through gzip :

To pass switches into your script, you can use one of the Getopts modules or put a loop on the front like this:

The <> symbol returns undef for end-of-file only once. If you call it again after this, it will assume you are processing another @ARGV list, and if you haven't set @ARGV , will read input from STDIN .

If what the angle brackets contain is a simple scalar variable (for example, <$foo> ), then that variable contains the name of the filehandle to input from, or its typeglob, or a reference to the same. For example:

If what's in the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it's interpreted as a filename pattern to be globbed, and either a list of filenames or the next file name in the list is returned, depending on context. This distinction is determined on syntactic grounds alone. That means <$x> is always a readline() from an indirect handle, but <$hash{key}> is always a glob() . That's because $x is a simple scalar variable, but $hash{key} is not: it's a hash element. Even <$x > (note the extra space) is treated as glob("$x ") , not readline($x) .

One level of double quote interpretation is done first, but you can't say <$foo> because that's an indirect filehandle as explained in the previous paragraph. In older versions of Perl, programmers would insert curly brackets to force interpretation as a filename glob: <${foo}> . These days, it's considered cleaner to call the internal function directly as glob($foo) , which is probably the right way to have done it in the first place. For example:

is roughly equivalent to:

except that the globbing is actually done internally using the standard File::Glob extension. Of course, the shortest way to do the above is:

A (file)glob evaluates its (embedded) argument only when it is starting a new list. All values must be read before it starts over. In list context, this isn't important because you automatically get them all. However, in scalar context the operator returns the next value each time it's called, or undef when the list has run out. As with filehandle reads, an automatic defined is generated when the glob occurs in the test part of a while , because legal glob returns (for example, a file called 0 ) would otherwise terminate the loop. Again, undef is returned only once. So if you're expecting a single value from a glob, it is much better to say

because the latter will alternate between returning a filename and returning false.

If you're trying to do variable interpolation, it's better to use the glob() function, because the older notation can cause people to become confused with the indirect filehandle notation.

Like C, Perl does a certain amount of expression evaluation at compile time whenever it determines that all arguments to an operator are static and have no side effects. In particular, string concatenation happens at compile time between literals that don't do variable substitution. Backslash interpolation also happens at compile time. You can say

and this all reduces to one string internally. Likewise, if you say

the compiler precomputes the number which that expression represents so that the interpreter won't have to.

Perl doesn't officially have a no-op operator, but the bare constants 0 and 1 are special-cased not to produce a warning in void context, so you can for example safely do

Bitwise String Operators

Bitstrings of any size may be manipulated by the bitwise operators (~ | & ^) .

If the operands to a binary bitwise op are strings of different sizes, | and ^ ops act as though the shorter operand had additional zero bits on the right, while the & op acts as though the longer operand were truncated to the length of the shorter. The granularity for such extension or truncation is one or more bytes.

If you are intending to manipulate bitstrings, be certain you're supplying bitstrings: If an operand is a number, that implies a numeric bitwise operation. You may explicitly show which type of operation you intend using "" or 0+ , as in the examples below.

See vec for information on how to manipulate individual bits in a bit vector.

By default, Perl assumes that it must do most of its arithmetic in floating point . But by saying

you may tell the compiler to use integer operations from here to the end of the enclosing BLOCK. An inner BLOCK may countermand this by saying

which lasts until the end of that BLOCK. Note that this doesn't mean everything is an integer, merely that Perl uses integer operations for arithmetic, comparison, and bitwise operators. For example, even under use integer , if you take the sqrt (2) , you'll still get 1.4142135623731 or so.

Used on numbers, the bitwise operators (" & ", " | ", " ^ ", " ~ ", " << ", and " >> ") always produce integral results. But see also Bitwise String Operators. However, use integer still has meaning for them. By default, their results are interpreted as unsigned integers, but if use integer is in effect, their results are interpreted as signed integers. For example, ~0 usually evaluates to a large integral value. However, use integer; ~0 is -1 on two's-complement machines.

Floating-Point Arithmetic

While use integer provides integer-only arithmetic, there is no analogous mechanism to provide automatic rounding or truncation to a certain number of decimal places. For rounding to a certain number of digits, sprintf() or printf() is usually the easiest route.

Floating-point numbers are only approximations to what a mathematician would call real numbers. There are infinitely more reals than floats, so some corners must be cut. For example:

Testing for exact floating-point equality or inequality is not a good idea. Here's a (relatively expensive) work-around to compare whether two floating-point numbers are equal to a particular number of decimal places.

The POSIX module (part of the standard perl distribution) implements ceil() , floor() , and other mathematical and trigonometric functions. The Math::Complex module (part of the standard perl distribution) defines mathematical functions that work on both the reals and the imaginary numbers. Math::Complex not as efficient as POSIX, but POSIX can't work with complex numbers.

Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is used by Perl, but to instead implement the rounding function you need yourself.

The standard Math::BigInt , Math::BigRat , and Math::BigFloat modules, along with the bignum , bigint , and bigrat pragmas, provide variable-precision arithmetic and overloaded operators, although they're currently pretty slow. At the cost of some space and considerable speed, they avoid the normal pitfalls associated with limited-precision representations.

Or with rationals:

Several modules let you calculate with (bound only by memory and CPU time) unlimited or fixed precision. There are also some non-standard modules that provide faster implementations via external C libraries.

Here is a short, but incomplete summary:

  • Perl Data Types
  • Perl Subroutines
  • Perl Functions
  • Perl Pragmas
  • Perl - Home
  • Perl - Introduction
  • Perl - Comments
  • Perl - Operators
  • Perl - If Else
  • Perl - Unless Else
  • Perl - Given Statement
  • Perl - While Loop
  • Perl - Until Loop
  • Perl - For Loop
  • Perl - Foreach Loop
  • Perl - goto Statement
  • Perl - Next Statement
  • Perl - Last Statement
  • Perl - Continue Statement
  • Perl - Redo Statement
  • Perl - Math Functions

AlphaCodingSkills

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

Perl - Bitwise OR and assignment operator

The Bitwise OR and assignment operator (|=) assigns the first operand a value equal to the result of Bitwise OR operation of two operands.

(x |= y) is equivalent to (x = x | y)

The Bitwise OR operator (|) is a binary operator which takes two bit patterns of equal length and performs the logical OR operation on each pair of corresponding bits. It returns 1 if either or both bits at the same position are 1, else returns 0.

The example below describes how bitwise OR operator works:

The code of using Bitwise OR operator (|) is given below:

The output of the above code will be:

Example: Find largest power of 2 less than or equal to given number

Consider an integer 1000. In the bit-wise format, it can be written as 1111101000. However, all bits are not written here. A complete representation will be 32 bit representation as given below:

Performing n |= (n>>i) operation, where i = 1, 2, 4, 8, 16 will change all right side bit to 1. When applied on 1000, the result in 32 bit representation is given below:

Adding one to this result and then right shifting the result by one place will give largest power of 2 less than or equal to 1000.

The below code will calculate the largest power of 2 less than or equal to given number.

The above code will give the following output:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

Assignment Operators

Get introduced to the functionality of the assignment and the combined assignment operator in this lesson.

Basic assignment

  • Explanation
  • Combined assignment
  • Difference between = and == operator

Perl allows you to do the basic arithmetic assignment by using the = operator.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy

perl defined or assignment operator

  • Onsite training

3,000,000+ delegates

15,000+ clients

1,000+ locations

  • KnowledgePass
  • Log a ticket

01344203999 Available 24/7

Perl Operator: A Comprehensive Overview

Discover this blog to explore an in-depth analysis of Perl Operator. This blog will also cover different types, including arithmetic, string, logical, and bitwise operators, explaining their syntax and usage. This blog also emphasises their role in controlling program flow and manipulating data, highlighting best practices for efficient coding in Perl.

stars

Exclusive 40% OFF

Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

  • Object Oriented Programming (OOPs) Course
  • Elixir Programming Language Training
  • D Programming Language Training
  • Clojure Programming Language Training
  • Rust Course

course

Perl is a versatile scripting language that offers a rich set of operators and essential tools for programmers to manipulate data and control program flow. Perl Operators are categorised into various types, such as arithmetic for mathematical operations, string operators for text manipulation, logical operators for decision-making, and more. Each type is unique, allowing for addition, concatenation, comparison, and condition evaluation.   

Understanding these operators is crucial for effective Perl programming, as they are fundamental in constructing expressions and enabling complex functionalities. Do you want to learn more about these Operators? Read this blog to learn more about Perl Operators and explore these powerful Operators and how they are used. 

Table of Contents 

1) What is Perl Operator? 

2) Arithmetic Operators 

3) Equality Operators 

4) Assignment Operators 

5) Bitwise Operators 

6) Logical Operators 

7) Conclusion 

What is a Perl Operator? 

Understanding Perl Operators is essential for any programmer working with the language. They allow for executing complex operations and control structures, rendering Perl an effective tool for various applications, from web development to system administration.   

In Perl, an Operator is a key element for executing specific operations on operands, which can be values or variables. These Operators are integral to forming expressions in Perl, enabling data manipulation and dictating program logic flow. The richness and variety of operators in Perl make it a versatile language suitable for various programming tasks.   

Operators in Perl are categorised into several types, each with its unique role. Arithmetic Operators, for instance, are used for basic mathematical operations like addition, subtraction, multiplication, and division. 

These are fundamental for any calculations within the program. String operators, on the other hand, are designed specifically for string manipulation, allowing for operations like concatenation, repetition, and string comparison. 

  

Basic Perl Programming Training

Arithmetic Operators 

Arithmetic operators, including Perl, are fundamental in any programming language as they allow for basic mathematical operations within the code. These operators enable the manipulation of numerical values, forming the backbone of many computational tasks. In Perl, arithmetic operators are intuitive and follow conventional mathematical notation, making them accessible to both beginners and experienced programmers.   

a)  Addition (+): The most basic arithmetic operator is addition, represented by the plus sign (+). It is used to add two or more numbers. For example, ‘$sum = $a + $b’; will add the values of ‘$a’ and ‘$b’ and store the result in ‘$sum’. 

my $a = 5; 

my $b = 3; 

my $sum = $a + $b;  

# $sum is 8 

b) Subtraction (-): The subtraction operator, denoted by a minus sign (-), subtracts one number from another. For instance, ‘$difference = $a - $b’; will subtract ‘$b’ from ‘$a’ 

my $a = 10; 

my $b = 4; 

my $difference = $a - $b;  

# $difference is 6 

c) Multiplication (*): Represented by an asterisk (*), the multiplication operator is used to multiply two numbers. ‘$product = $a * $b’; multiplies ‘$a’ and ‘$b’. 

my $a = 7; 

my $b = 6; 

my $product = $a * $b; 

# $product is 42 

d) Division (/): The division operator, symbolised by a forward slash (/), divides one number by another. ‘$quotient = $a / $b’; will divide ‘$a’ by ‘$b’. 

my $a = 20; 

my $b = 5; 

my $quotient = $a / $b;  

# $quotient is 4 

e) Modulus (%): The modulus operator, represented by a percent sign (%), is used to find the remainder of a division operation. ‘$remainder = $a % $b’; will give the remainder when ‘$a’ is divided by ‘$b’. 

my $remainder = $a % $b;  

# $remainder is 1 

f) Exponentiation (): Perl also supports exponentiation (raising a number to the power of another number) using the double asterisk operator (). ‘$power = $a ** $b’; will raise ‘$a’ to the power of ‘$b’. 

my $a = 2; 

my $power = $a ** $b;  

# $power is 8 

g) Auto-increment (++) and Auto-decrement (--): Perl provides two very useful arithmetic operators: auto-increment (++) and auto-decrement (--). The auto-increment operator increases a number's value by one, while the auto-decrement operator decreases it by one. These operators can be used both as pre- and post-operators. 

my $value = 5; 

$value++; # $value is now 6 

$value--; # $value is back to 5 

h) Assignment with Arithmetic Operators: Perl combines assignment with arithmetic operators, enabling shorthand operations. For example, $a += $b; is equivalent to $a = $a + $b;. 

$a += 5; # $a is now 15 

$a *= 2; # $a is now 30 

Equality Operators 

In Perl, Equality Operators are essential for comparing values, a fundamental aspect of programming that allows for decision-making based on conditions. These operators test for equality or inequality, yielding Boolean values (true or false). Understanding equality operators is crucial for controlling program flow through conditional statements like ‘if’, ‘unless’, ‘while’, and others. 

Types of Equality Operators in Perl: 

Perl distinguishes between two types of equality comparisons: numeric and string. This distinction is crucial because Perl is a context-sensitive language, meaning it treats the same data differently based on the context. 

a) Numeric Equality Operators 

1) Equal (==): This operator checks if two numbers are equal. If they are, it returns true; otherwise, it returns false. 

if ($a == $b) { 

    print "a and b are equal"; 

2) Not equal (!=): It tests whether two numbers are not equal. If they are different, it returns true. 

if ($a != $b) { 

    print "a and b are not equal"; 

b) String Equality Operators 

1.    Equal (eq): This operator checks whether two strings are identical. It's essential to use eq instead of == when comparing strings. 

if ($string1 eq $string2) { 

    print "The strings are equal"; 

2.    Not equal (ne): It checks if two strings are different. 

if ($string1 ne $string2) { 

    print "The strings are not equal"; 

Assignment Operators 

Assignment operators in programming languages like Perl are fundamental components that simplify assigning values to variables. They are not just limited to the basic assignment but also include a range of compound assignment operators that combine arithmetic, string, and other operations with the assignment. Understanding these operators is crucial for writing concise and efficient code. 

a)  Basic Assignment Operator 

1) Equals (=): The most basic assignment operator is the equals sign (=). It assigns the value on its right to the variable on its left.  

my $a = 5;  # Assigns 5 to $a 

b) Compound Assignment Operators: 

Perl enhances the functionality of the basic assignment operator with compound assignment operators, which combine an operation with the assignment.   

1)  Addition Assignment (+=): Adds the right operand to the left operand and assigns the result to the left operand. 

 $a += 3;  # Equivalent to $a = $a + 3 

2) Subtraction Assignment (-=): Subtracts the right operand from the left operand and assigns the result to the left operand. 

 $a -= 2;  # Equivalent to $a = $a - 2 

3) Multiplication Assignment (*=): Multiplies the left operand by the right operand and assigns the result to the left operand. 

 $a *= 4;  # Equivalent to $a = $a * 4 

4) Division Assignment (/=): Divides the left operand by the right operand and assigns the result to the left operand. 

 $a /= 2;  # Equivalent to $a = $a / 2 

5) Modulus Assignment (%=): Applies modulus operation and assigns the result to the left operand. 

 $a %= 3;  # Equivalent to $a = $a % 3 

6) Exponentiation Assignment (**=): Raises the left operand to the power of the right operand and assigns the result back. 

 $a **= 2;  # Equivalent to $a = $a ** 2 

7) String Concatenation Assignment (.=): Appends the right string operand to the left string operand.  

my $str = "Hello"; 

$str .= " World";  # $str now is "Hello World" 

8) Bitwise AND Assignment (&=), Bitwise OR Assignment (|=), and Bitwise XOR Assignment (^=): These perform the corresponding bitwise operation and assign the result to the left operand. 

$a &= $b;  # Bitwise AND 

$a |= $b;  # Bitwise OR 

$a ^= $b;  # Bitwise XOR 

Bitwise Operators 

Bitwise Operators are a category of operators in programming languages, such as Perl, that perform operations at the bit level on numeric values. These operators treat their operands as sequences of 32 or 64 bits (depending on the platform) and operate on them bit by bit.  

Understanding bitwise operators is essential for tasks involving low-level data manipulation, such as working with binary data, flags, and masks.  

Types of Bitwise Operators: 

1) AND (&): The bitwise AND operator compares each bit of its first operand to the corresponding bit of its second operand. If both bits are 1, it sets the bit in the result to 1; otherwise, it is 0. 

 $result = $a & $b;  # Bitwise AND of $a and $b 

2) OR (|): This operator compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1, it sets the result bit to 1. 

 $result = $a | $b;  # Bitwise OR of $a and $b 

3) XOR (^): The bitwise XOR (exclusive OR) operator compares each bit of its first operand to the corresponding bit of its second operand. If the bits are different, it sets the result bit to 1. 

 $result = $a ^ $b;  # Bitwise XOR of $a and $b 

4) NOT (~): The bitwise NOT operator inverts all the bits of its operand. 

 $result = ~$a;  # Bitwise NOT of $a 

5) Left Shift ( This operator shifts all bits of its first operand to the left by the number of places specified in the second operand. New bits on the right are filled with zeros. 

 $result = $a << $shift;  # Left shift $a by $shift bits 

6) Right Shift (>>): It shifts all bits of its first operand to the right. The behaviour for the leftmost bits depends on the number type and whether it's signed or unsigned. 

 $result = $a >> $shift;  # Right shift $a by $shift bits 

Become an expert in different Programming Languages – sign up now with our course on Programming Training !  

Logical Operators 

Logical operators in Perl are crucial for constructing logical expressions, which are fundamental to controlling program flow through conditional statements like ‘if’, ‘while’, and ‘unless’. These operators evaluate expressions and return Boolean values (true or false) based on the logic they implement. The primary logical operators in Perl are ‘and’, ‘or’, ‘not’, ‘&&’, ‘||’, and ‘!’.   

Types of Logical Operators: 

1) AND (&& and ‘and’): This operator returns true if both operands are true. The difference between ‘&’ and ‘and’ is their precedence, with && having a higher precedence. 

 if ($a && $b) { 

    # Executes if both $a and $b are true 

2) OR (|| and or): The OR operator returns true if either of its operands is true. Similar to AND, ‘||’ has a higher precedence than ‘or’.  

if ($a || $b) { 

    # Executes if either $a or $b is true 

3) NOT (! and not): NOT is a unary operator that inverts the truth value of its operand. ! has a higher precedence than not. 

 if (!$a) { 

    # Executes if $a is not true (i.e., false) 

Do you want to learn more about Perl Programming Language? Register now for our Basic Perl Programming Training !  

Conclusion 

Perl Operators are fundamental tools that greatly enhance the language's power and flexibility. They enable efficient data manipulation, logical decision-making, and control over program flow. Mastering these operators, from arithmetic to logical, is crucial for effective Perl scripting, allowing for concise and powerful code in various applications. 

Learn the concept of data reshaping with R Programming – join now for our R Programming Course !  

Frequently Asked Questions

The most commonly used Perl operators are:  

a) Arithmetic Operators (+, -, *, /, %) for basic mathematical operations. 

b) String Operators (. for concatenation, x for repetition) for string manipulation. 

c) Logical Operators (&&, ||, !) for evaluating Boolean expressions and controlling program flow.   

Perl uses different operators for numeric and string comparison. For numeric comparison, it uses ‘==’ (equal), ‘!=’ (not equal), ‘ ’ (greater than), etc. For string comparison, it uses ‘eq’ (equal), ‘ne’ (not equal), ‘lt’ (less than), ‘gt’ (greater than), etc. This distinction ensures accurate comparisons based on the data type. 

Yes, Perl operators can be combined to form complex expressions. For instance, arithmetic operators can be used with assignment operators (like +=, *=) for compound assignments. Logical operators can be used to combine multiple conditions in control structures. However, it's important to remember operator precedence and use parentheses for clarity when needed. 

The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.   

Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs , videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA .  

The Knowledge Academy’s Knowledge Pass , a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.   

The Knowledge Academy offers various Programming courses , including Basic Perl Programming Training, PHP Course, and R Programming Course. These courses cater to different skill levels, providing comprehensive insights into Programming Languages .  

Our Programming blogs covers a range of topics related to Perl, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered. 

Upcoming Programming & DevOps Resources Batches & Dates

Thu 9th May 2024

Thu 29th Aug 2024

Thu 28th Nov 2024

Get A Quote

WHO WILL BE FUNDING THE COURSE?

My employer

By submitting your details you agree to be contacted in order to respond to your enquiry

  • Business Analysis
  • Lean Six Sigma Certification

Share this course

Our biggest spring sale.

red-star

We cannot process your enquiry without contacting you, please tick to confirm your consent to us for contacting you about your enquiry.

By submitting your details you agree to be contacted in order to respond to your enquiry.

We may not have the course you’re looking for. If you enquire or give us a call on 01344203999 and speak to our training experts, we may still be able to help with your training requirements.

Or select from our popular topics

  • ITIL® Certification
  • Scrum Certification
  • Change Management Certification
  • Business Analysis Courses
  • Microsoft Azure Certification
  • Microsoft Excel Courses
  • Microsoft Project
  • Explore more courses

Press esc to close

Fill out your  contact details  below and our training experts will be in touch.

Fill out your   contact details   below

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

Back to Course Information

Fill out your contact details below so we can get in touch with you regarding your training requirements.

* WHO WILL BE FUNDING THE COURSE?

Preferred Contact Method

No preference

Back to course information

Fill out your  training details  below

Fill out your training details below so we have a better idea of what your training requirements are.

HOW MANY DELEGATES NEED TRAINING?

HOW DO YOU WANT THE COURSE DELIVERED?

Online Instructor-led

Online Self-paced

WHEN WOULD YOU LIKE TO TAKE THIS COURSE?

Next 2 - 4 months

WHAT IS YOUR REASON FOR ENQUIRING?

Looking for some information

Looking for a discount

I want to book but have questions

One of our training experts will be in touch shortly to go overy your training requirements.

Your privacy & cookies!

Like many websites we use cookies. We care about your data and experience, so to give you the best possible experience using our site, we store a very limited amount of your data. Continuing to use this site or clicking “Accept & close” means that you agree to our use of cookies. Learn more about our privacy policy and cookie policy cookie policy .

We use cookies that are essential for our site to work. Please visit our cookie policy for more information. To accept all cookies click 'Accept & close'.

Perl - Assignment Operator

Learn Perl Assignment operator with code examples.

This tutorial explains about Perl assignment Operators

Perl assignments operators

Assignment operators perform expression and assign the result to a variable.

  • Simple assignment
  • Assignment Addition
  • Assignment Subtraction
  • Assignment Multiplication
  • Assignment Division
  • Assignment Modulus
  • Assignment Exponent

Perl Assignment Operator

For example, We have operand1(op1)=6 and operand2(op2) =2 values.

Here is a Perl Assignment Operator Example

What Assignment operators are used in Perl scripts?

Arithmetic operators with assignments in Perl allow you to do arithmetic calculations on operands, and assign the result to a left operand. Addition(+=),Multiplication(*=),Subtraction(-=), Division(/=), Modulus(%=), Exponent(power (**=)) operators exists for this.

What are Assignment operators in Perl

there are 6 operators in Per for Assignment operators. Addition(+=),Multiplication(*=),Subtraction(-=), Division(/=), Modulus(%=), Exponent(power (**=)) operators exists for this.

  • Declaration
  • Calling Conventions and Magic Autogeneration
  • Mathemagic, Mutators, and Copy Constructors
  • Overloadable Operations
  • Minimal Set of Overloaded Operations
  • Copy Constructor
  • How Perl Chooses an Operator Implementation
  • Losing Overloading
  • Inheritance and Overloading
  • Run-time Overloading
  • Public Functions
  • Overloading Constants
  • IMPLEMENTATION
  • Two-face Scalars
  • Two-face References
  • Symbolic Calculator
  • Really Symbolic Calculator
  • DIAGNOSTICS
  • BUGS AND PITFALLS

overload - Package for overloading Perl operations

# DESCRIPTION

This pragma allows overloading of Perl's operators for a class. To overload built-in functions, see "Overriding Built-in Functions" in perlsub instead.

# Fundamentals

# declaration.

Arguments of the use overload directive are (key, value) pairs. For the full set of legal keys, see "Overloadable Operations" below.

Operator implementations (the values) can be subroutines, references to subroutines, or anonymous subroutines - in other words, anything legal inside a &{ ... } call. Values specified as strings are interpreted as method names. Thus

declares that subtraction is to be implemented by method minus() in the class Number (or one of its base classes), and that the function Number::muas() is to be used for the assignment form of multiplication, *= . It also defines an anonymous subroutine to implement stringification: this is called whenever an object blessed into the package Number is used in a string context (this subroutine might, for example, return the number as a Roman numeral).

# Calling Conventions and Magic Autogeneration

The following sample implementation of minus() (which assumes that Number objects are simply blessed references to scalars) illustrates the calling conventions:

Three arguments are passed to all subroutines specified in the use overload directive (with exceptions - see below, particularly "nomethod" ).

The first of these is the operand providing the overloaded operator implementation - in this case, the object whose minus() method is being called.

The second argument is the other operand, or undef in the case of a unary operator.

The third argument is set to TRUE if (and only if) the two operands have been swapped. Perl may do this to ensure that the first argument ( $self ) is an object implementing the overloaded operation, in line with general object calling conventions. For example, if $x and $y are Number s:

Perl may also use minus() to implement other operators which have not been specified in the use overload directive, according to the rules for "Magic Autogeneration" described later. For example, the use overload above declared no subroutine for any of the operators -- , neg (the overload key for unary minus), or -= . Thus

Note the undef s: where autogeneration results in the method for a standard operator which does not change either of its operands, such as - , being used to implement an operator which changes the operand ("mutators": here, -- and -= ), Perl passes undef as the third argument. This still evaluates as FALSE, consistent with the fact that the operands have not been swapped, but gives the subroutine a chance to alter its behaviour in these cases.

In all the above examples, minus() is required only to return the result of the subtraction: Perl takes care of the assignment to $x. In fact, such methods should not modify their operands, even if undef is passed as the third argument (see "Overloadable Operations" ).

The same is not true of implementations of ++ and -- : these are expected to modify their operand. An appropriate implementation of -- might look like

If the "bitwise" feature is enabled (see feature ), a fifth TRUE argument is passed to subroutines handling & , | , ^ and ~ . This indicates that the caller is expecting numeric behaviour. The fourth argument will be undef , as that position ( $_[3] ) is reserved for use by "nomethod" .

# Mathemagic, Mutators, and Copy Constructors

The term 'mathemagic' describes the overloaded implementation of mathematical operators. Mathemagical operations raise an issue. Consider the code:

If $a and $b are scalars then after these statements

An object, however, is a reference to blessed data, so if $a and $b are objects then the assignment $a = $b copies only the reference, leaving $a and $b referring to the same object data. One might therefore expect the operation --$a to decrement $b as well as $a . However, this would not be consistent with how we expect the mathematical operators to work.

Perl resolves this dilemma by transparently calling a copy constructor before calling a method defined to implement a mutator ( -- , += , and so on.). In the above example, when Perl reaches the decrement statement, it makes a copy of the object data in $a and assigns to $a a reference to the copied data. Only then does it call decr() , which alters the copied data, leaving $b unchanged. Thus the object metaphor is preserved as far as possible, while mathemagical operations still work according to the arithmetic metaphor.

Note: the preceding paragraph describes what happens when Perl autogenerates the copy constructor for an object based on a scalar. For other cases, see "Copy Constructor" .

# Overloadable Operations

The complete list of keys that can be specified in the use overload directive are given, separated by spaces, in the values of the hash %overload::ops :

Most of the overloadable operators map one-to-one to these keys. Exceptions, including additional overloadable operations not apparent from this hash, are included in the notes which follow. This list is subject to growth over time.

A warning is issued if an attempt is made to register an operator not found above.

The operator not is not a valid key for use overload . However, if the operator ! is overloaded then the same implementation will be used for not (since the two operators differ only in precedence).

The key neg is used for unary minus to disambiguate it from binary - .

Assuming they are to behave analogously to Perl's ++ and -- , overloaded implementations of these operators are required to mutate their operands.

No distinction is made between prefix and postfix forms of the increment and decrement operators: these differ only in the point at which Perl calls the associated subroutine when evaluating an expression.

Assignments

Simple assignment is not overloadable (the '=' key is used for the "Copy Constructor" ). Perl does have a way to make assignments to an object do whatever you want, but this involves using tie(), not overload - see "tie" in perlfunc and the "COOKBOOK" examples below.

The subroutine for the assignment variant of an operator is required only to return the result of the operation. It is permitted to change the value of its operand (this is safe because Perl calls the copy constructor first), but this is optional since Perl assigns the returned value to the left-hand operand anyway.

An object that overloads an assignment operator does so only in respect of assignments to that object. In other words, Perl never calls the corresponding methods with the third argument (the "swap" argument) set to TRUE. For example, the operation

cannot lead to $b 's implementation of *= being called, even if $a is a scalar. (It can, however, generate a call to $b 's method for * ).

Non-mutators with a mutator variant

As described above , Perl may call methods for operators like + and & in the course of implementing missing operations like ++ , += , and &= . While these methods may detect this usage by testing the definedness of the third argument, they should in all cases avoid changing their operands. This is because Perl does not call the copy constructor before invoking these methods.

Traditionally, the Perl function int rounds to 0 (see "int" in perlfunc ), and so for floating-point-like types one should follow the same semantic.

String, numeric, boolean, and regexp conversions

These conversions are invoked according to context as necessary. For example, the subroutine for '""' (stringify) may be used where the overloaded object is passed as an argument to print , and that for 'bool' where it is tested in the condition of a flow control statement (like while ) or the ternary ?: operation.

Of course, in contexts like, for example, $obj + 1 , Perl will invoke $obj 's implementation of + rather than (in this example) converting $obj to a number using the numify method '0+' (an exception to this is when no method has been provided for '+' and "fallback" is set to TRUE).

The subroutines for '""' , '0+' , and 'bool' can return any arbitrary Perl value. If the corresponding operation for this value is overloaded too, the operation will be called again with this value.

As a special case if the overload returns the object itself then it will be used directly. An overloaded conversion returning the object is probably a bug, because you're likely to get something that looks like YourPackage=HASH(0x8172b34) .

The subroutine for 'qr' is used wherever the object is interpolated into or used as a regexp, including when it appears on the RHS of a =~ or !~ operator.

qr must return a compiled regexp, or a ref to a compiled regexp (such as qr// returns), and any further overloading on the return value will be ignored.

If <> is overloaded then the same implementation is used for both the read-filehandle syntax <$var> and globbing syntax <${var}> .

The key '-X' is used to specify a subroutine to handle all the filetest operators ( -f , -x , and so on: see "-X" in perlfunc for the full list); it is not possible to overload any filetest operator individually. To distinguish them, the letter following the '-' is passed as the second argument (that is, in the slot that for binary operators is used to pass the second operand).

Calling an overloaded filetest operator does not affect the stat value associated with the special filehandle _ . It still refers to the result of the last stat , lstat or unoverloaded filetest.

This overload was introduced in Perl 5.12.

The key "~~" allows you to override the smart matching logic used by the ~~ operator and the switch construct ( given / when ). See "Switch Statements" in perlsyn and feature .

Unusually, the overloaded implementation of the smart match operator does not get full control of the smart match behaviour. In particular, in the following code:

the smart match does not invoke the method call like this:

rather, the smart match distributive rule takes precedence, so $obj is smart matched against each array element in turn until a match is found, so you may see between one and three of these calls instead:

Consult the match table in "Smartmatch Operator" in perlop for details of when overloading is invoked.

Dereferencing

If these operators are not explicitly overloaded then they work in the normal way, yielding the underlying scalar, array, or whatever stores the object data (or the appropriate error message if the dereference operator doesn't match it). Defining a catch-all 'nomethod' (see below ) makes no difference to this as the catch-all function will not be called to implement a missing dereference operator.

If a dereference operator is overloaded then it must return a reference of the appropriate type (for example, the subroutine for key '${}' should return a reference to a scalar, not a scalar), or another object which overloads the operator: that is, the subroutine only determines what is dereferenced and the actual dereferencing is left to Perl. As a special case, if the subroutine returns the object itself then it will not be called again - avoiding infinite recursion.

See "Special Keys for use overload " .

# Magic Autogeneration

If a method for an operation is not found then Perl tries to autogenerate a substitute implementation from the operations that have been defined.

Note: the behaviour described in this section can be disabled by setting fallback to FALSE (see "fallback" ).

In the following tables, numbers indicate priority. For example, the table below states that, if no implementation for '!' has been defined then Perl will implement it using 'bool' (that is, by inverting the value returned by the method for 'bool' ); if boolean conversion is also unimplemented then Perl will use '0+' or, failing that, '""' .

Note: The iterator ( '<>' ) and file test ( '-X' ) operators work as normal: if the operand is not a blessed glob or IO reference then it is converted to a string (using the method for '""' , '0+' , or 'bool' ) to be interpreted as a glob or filename.

Just as numeric comparisons can be autogenerated from the method for '<=>' , string comparisons can be autogenerated from that for 'cmp' :

Similarly, autogeneration for keys '+=' and '++' is analogous to '-=' and '--' above:

And other assignment variations are analogous to '+=' and '-=' (and similar to '.=' and 'x=' above):

Note also that the copy constructor (key '=' ) may be autogenerated, but only for objects based on scalars. See "Copy Constructor" .

# Minimal Set of Overloaded Operations

Since some operations can be automatically generated from others, there is a minimal set of operations that need to be overloaded in order to have the complete set of overloaded operations at one's disposal. Of course, the autogenerated operations may not do exactly what the user expects. The minimal set is:

Of the conversions, only one of string, boolean or numeric is needed because each can be generated from either of the other two.

# Special Keys for use overload

The 'nomethod' key is used to specify a catch-all function to be called for any operator that is not individually overloaded. The specified function will be passed four parameters. The first three arguments coincide with those that would have been passed to the corresponding method if it had been defined. The fourth argument is the use overload key for that missing method. If the "bitwise" feature is enabled (see feature ), a fifth TRUE argument is passed to subroutines handling & , | , ^ and ~ to indicate that the caller is expecting numeric behaviour.

For example, if $a is an object blessed into a package declaring

then the operation

could (unless a method is specifically declared for the key '+' ) result in a call

See "How Perl Chooses an Operator Implementation" .

The value assigned to the key 'fallback' tells Perl how hard it should try to find an alternative way to implement a missing operator.

defined, but FALSE

This disables "Magic Autogeneration" .

In the default case where no value is explicitly assigned to fallback , magic autogeneration is enabled.

The same as for undef , but if a missing operator cannot be autogenerated then, instead of issuing an error message, Perl is allowed to revert to what it would have done for that operator if there had been no use overload directive.

Note: in most cases, particularly the "Copy Constructor" , this is unlikely to be appropriate behaviour.

# Copy Constructor

As mentioned above , this operation is called when a mutator is applied to a reference that shares its object with some other reference. For example, if $b is mathemagical, and '++' is overloaded with 'incr' , and '=' is overloaded with 'clone' , then the code

would be executed in a manner equivalent to

The subroutine for '=' does not overload the Perl assignment operator: it is used only to allow mutators to work as described here. (See "Assignments" above.)

As for other operations, the subroutine implementing '=' is passed three arguments, though the last two are always undef and '' .

The copy constructor is called only before a call to a function declared to implement a mutator, for example, if ++$b; in the code above is effected via a method declared for key '++' (or 'nomethod', passed '++' as the fourth argument) or, by autogeneration, '+=' . It is not called if the increment operation is effected by a call to the method for '+' since, in the equivalent code,

the data referred to by $a is unchanged by the assignment to $b of a reference to new object data.

The copy constructor is not called if Perl determines that it is unnecessary because there is no other reference to the data being modified.

If 'fallback' is undefined or TRUE then a copy constructor can be autogenerated, but only for objects based on scalars. In other cases it needs to be defined explicitly. Where an object's data is stored as, for example, an array of scalars, the following might be appropriate:

If 'fallback' is TRUE and no copy constructor is defined then, for objects not based on scalars, Perl may silently fall back on simple assignment - that is, assignment of the object reference. In effect, this disables the copy constructor mechanism since no new copy of the object data is created. This is almost certainly not what you want. (It is, however, consistent: for example, Perl's fallback for the ++ operator is to increment the reference itself.)

# How Perl Chooses an Operator Implementation

Which is checked first, nomethod or fallback ? If the two operands of an operator are of different types and both overload the operator, which implementation is used? The following are the precedence rules:

If the first operand has declared a subroutine to overload the operator then use that implementation.

Otherwise, if fallback is TRUE or undefined for the first operand then see if the rules for autogeneration allows another of its operators to be used instead.

Unless the operator is an assignment ( += , -= , etc.), repeat step (1) in respect of the second operand.

Repeat Step (2) in respect of the second operand.

If the first operand has a "nomethod" method then use that.

If the second operand has a "nomethod" method then use that.

If fallback is TRUE for both operands then perform the usual operation for the operator, treating the operands as numbers, strings, or booleans as appropriate for the operator (see note).

Nothing worked - die.

Where there is only one operand (or only one operand with overloading) the checks in respect of the other operand above are skipped.

There are exceptions to the above rules for dereference operations (which, if Step 1 fails, always fall back to the normal, built-in implementations - see Dereferencing), and for ~~ (which has its own set of rules - see Matching under "Overloadable Operations" above).

Note on Step 7: some operators have a different semantic depending on the type of their operands. As there is no way to instruct Perl to treat the operands as, e.g., numbers instead of strings, the result here may not be what you expect. See "BUGS AND PITFALLS" .

# Losing Overloading

The restriction for the comparison operation is that even if, for example, cmp should return a blessed reference, the autogenerated lt function will produce only a standard logical value based on the numerical value of the result of cmp . In particular, a working numeric conversion is needed in this case (possibly expressed in terms of other conversions).

Similarly, .= and x= operators lose their mathemagical properties if the string conversion substitution is applied.

When you chop() a mathemagical object it is promoted to a string and its mathemagical properties are lost. The same can happen with other operations as well.

# Inheritance and Overloading

Overloading respects inheritance via the @ISA hierarchy. Inheritance interacts with overloading in two ways.

If value in

is a string, it is interpreted as a method name - which may (in the usual way) be inherited from another class.

Any class derived from an overloaded class is also overloaded and inherits its operator implementations. If the same operator is overloaded in more than one ancestor then the implementation is determined by the usual inheritance rules.

For example, if A inherits from B and C (in that order), B overloads + with \&D::plus_sub , and C overloads + by "plus_meth" , then the subroutine D::plus_sub will be called to implement operation + for an object in package A .

Note that in Perl version prior to 5.18 inheritance of the fallback key was not governed by the above rules. The value of fallback in the first overloaded ancestor was used. This was fixed in 5.18 to follow the usual rules of inheritance.

# Run-time Overloading

Since all use directives are executed at compile-time, the only way to change overloading during run-time is to

You can also use

though the use of these constructs during run-time is questionable.

# Public Functions

Package overload.pm provides the following public functions:

Gives the string value of arg as in the absence of stringify overloading. If you are using this to get the address of a reference (useful for checking if two references point to the same thing) then you may be better off using builtin::refaddr() or Scalar::Util::refaddr() , which are faster.

Returns true if arg is subject to overloading of some operations.

Returns undef or a reference to the method that implements op .

Such a method always takes three arguments, which will be enforced if it is an XS method.

# Overloading Constants

For some applications, the Perl parser mangles constants too much. It is possible to hook into this process via overload::constant() and overload::remove_constant() functions.

These functions take a hash as an argument. The recognized keys of this hash are:

to overload integer constants,

to overload floating point constants,

to overload octal and hexadecimal constants,

to overload q -quoted strings, constant pieces of qq - and qx -quoted strings and here-documents,

to overload constant pieces of regular expressions.

The corresponding values are references to functions which take three arguments: the first one is the initial string form of the constant, the second one is how Perl interprets this constant, the third one is how the constant is used. Note that the initial string form does not contain string delimiters, and has backslashes in backslash-delimiter combinations stripped (thus the value of delimiter is not relevant for processing of this string). The return value of this function is how this constant is going to be interpreted by Perl. The third argument is undefined unless for overloaded q - and qr - constants, it is q in single-quote context (comes from strings, regular expressions, and single-quote HERE documents), it is tr for arguments of tr / y operators, it is s for right-hand side of s -operator, and it is qq otherwise.

Since an expression "ab$cd,," is just a shortcut for 'ab' . $cd . ',,' , it is expected that overloaded constant strings are equipped with reasonable overloaded catenation operator, otherwise absurd results will result. Similarly, negative numbers are considered as negations of positive constants.

Note that it is probably meaningless to call the functions overload::constant() and overload::remove_constant() from anywhere but import() and unimport() methods. From these methods they may be called as

# IMPLEMENTATION

What follows is subject to change RSN.

The table of methods for all operations is cached in magic for the symbol table hash for the package. The cache is invalidated during processing of use overload , no overload , new function definitions, and changes in @ISA.

(Every SVish thing has a magic queue, and magic is an entry in that queue. This is how a single variable may participate in multiple forms of magic simultaneously. For instance, environment variables regularly have two forms at once: their %ENV magic and their taint magic. However, the magic which implements overloading is applied to the stashes, which are rarely used directly, thus should not slow down Perl.)

If a package uses overload, it carries a special flag. This flag is also set when new functions are defined or @ISA is modified. There will be a slight speed penalty on the very first operation thereafter that supports overloading, while the overload tables are updated. If there is no overloading present, the flag is turned off. Thus the only speed penalty thereafter is the checking of this flag.

It is expected that arguments to methods that are not explicitly supposed to be changed are constant (but this is not enforced).

Please add examples to what follows!

# Two-face Scalars

Put this in two_face.pm in your Perl library directory:

Use it as follows:

(The second line creates a scalar which has both a string value, and a numeric value.) This prints:

# Two-face References

Suppose you want to create an object which is accessible as both an array reference and a hash reference.

Now one can access an object using both the array and hash syntax:

Note several important features of this example. First of all, the actual type of $bar is a scalar reference, and we do not overload the scalar dereference. Thus we can get the actual non-overloaded contents of $bar by just using $$bar (what we do in functions which overload dereference). Similarly, the object returned by the TIEHASH() method is a scalar reference.

Second, we create a new tied hash each time the hash syntax is used. This allows us not to worry about a possibility of a reference loop, which would lead to a memory leak.

Both these problems can be cured. Say, if we want to overload hash dereference on a reference to an object which is implemented as a hash itself, the only problem one has to circumvent is how to access this actual hash (as opposed to the virtual hash exhibited by the overloaded dereference operator). Here is one possible fetching routine:

To remove creation of the tied hash on each access, one may an extra level of indirection which allows a non-circular structure of references:

Now if $baz is overloaded like this, then $baz is a reference to a reference to the intermediate array, which keeps a reference to an actual array, and the access hash. The tie()ing object for the access hash is a reference to a reference to the actual array, so

There are no loops of references.

Both "objects" which are blessed into the class two_refs1 are references to a reference to an array, thus references to a scalar . Thus the accessor expression $$foo->[$ind] involves no overloaded operations.

# Symbolic Calculator

Put this in symbolic.pm in your Perl library directory:

This module is very unusual as overloaded modules go: it does not provide any usual overloaded operators, instead it provides an implementation for "nomethod" . In this example the nomethod subroutine returns an object which encapsulates operations done over the objects: symbolic->new(3) contains ['n', 3] , 2 + symbolic->new(3) contains ['+', 2, ['n', 3]] .

Here is an example of the script which "calculates" the side of circumscribed octagon using the above package:

The value of $side is

Note that while we obtained this value using a nice little script, there is no simple way to use this value. In fact this value may be inspected in debugger (see perldebug ), but only if bareStringify O ption is set, and not via p command.

If one attempts to print this value, then the overloaded operator "" will be called, which will call nomethod operator. The result of this operator will be stringified again, but this result is again of type symbolic , which will lead to an infinite loop.

Add a pretty-printer method to the module symbolic.pm :

Now one can finish the script by

The method pretty is doing object-to-string conversion, so it is natural to overload the operator "" using this method. However, inside such a method it is not necessary to pretty-print the components $a and $b of an object. In the above subroutine "[$meth $a $b]" is a catenation of some strings and components $a and $b. If these components use overloading, the catenation operator will look for an overloaded operator . ; if not present, it will look for an overloaded operator "" . Thus it is enough to use

Now one can change the last line of the script to

which outputs

and one can inspect the value in debugger using all the possible methods.

Something is still amiss: consider the loop variable $cnt of the script. It was a number, not an object. We cannot make this value of type symbolic , since then the loop will not terminate.

Indeed, to terminate the cycle, the $cnt should become false. However, the operator bool for checking falsity is overloaded (this time via overloaded "" ), and returns a long string, thus any object of type symbolic is true. To overcome this, we need a way to compare an object to 0. In fact, it is easier to write a numeric conversion routine.

Here is the text of symbolic.pm with such a routine added (and slightly modified str()):

All the work of numeric conversion is done in %subr and num(). Of course, %subr is not complete, it contains only operators used in the example below. Here is the extra-credit question: why do we need an explicit recursion in num()? (Answer is at the end of this section.)

Use this module like this:

It prints (without so many line breaks)

The above module is very primitive. It does not implement mutator methods ( ++ , -= and so on), does not do deep copying (not required without mutators!), and implements only those arithmetic operations which are used in the example.

To implement most arithmetic operations is easy; one should just use the tables of operations, and change the code which fills %subr to

Since subroutines implementing assignment operators are not required to modify their operands (see "Overloadable Operations" above), we do not need anything special to make += and friends work, besides adding these operators to %subr and defining a copy constructor (needed since Perl has no way to know that the implementation of '+=' does not mutate the argument - see "Copy Constructor" ).

To implement a copy constructor, add '=' => \&cpy to use overload line, and code (this code assumes that mutators change things one level deep only, so recursive copying is not needed):

To make ++ and -- work, we need to implement actual mutators, either directly, or in nomethod . We continue to do things inside nomethod , thus add

after the first line of wrap(). This is not a most effective implementation, one may consider

As a final remark, note that one can fill %subr by

This finishes implementation of a primitive symbolic calculator in 50 lines of Perl code. Since the numeric values of subexpressions are not cached, the calculator is very slow.

Here is the answer for the exercise: In the case of str(), we need no explicit recursion since the overloaded . -operator will fall back to an existing overloaded operator "" . Overloaded arithmetic operators do not fall back to numeric conversion if fallback is not explicitly requested. Thus without an explicit recursion num() would convert ['+', $a, $b] to $a + $b , which would just rebuild the argument of num().

If you wonder why defaults for conversion are different for str() and num(), note how easy it was to write the symbolic calculator. This simplicity is due to an appropriate choice of defaults. One extra note: due to the explicit recursion num() is more fragile than sym(): we need to explicitly check for the type of $a and $b. If components $a and $b happen to be of some related type, this may lead to problems.

# Really Symbolic Calculator

One may wonder why we call the above calculator symbolic. The reason is that the actual calculation of the value of expression is postponed until the value is used .

To see it in action, add a method

to the package symbolic . After this change one can do

and the numeric value of $c becomes 5. However, after calling

the numeric value of $c becomes 13. There is no doubt now that the module symbolic provides a symbolic calculator indeed.

To hide the rough edges under the hood, provide a tie()d interface to the package symbolic . Add methods

(the bug, fixed in Perl 5.14, is described in "BUGS" ). One can use this new interface as

Now numeric value of $c is 5. After $a = 12; $b = 5 the numeric value of $c becomes 13. To insulate the user of the module add a method

shows that the numeric value of $c follows changes to the values of $a and $b.

Ilya Zakharevich < [email protected] >.

The overloading pragma can be used to enable or disable overloaded operations within a lexical scope - see overloading .

# DIAGNOSTICS

When Perl is run with the -Do switch or its equivalent, overloading induces diagnostic messages.

Using the m command of Perl debugger (see perldebug ) one can deduce which operations are overloaded (and which ancestor triggers this overloading). Say, if eq is overloaded, then the method (eq is shown by debugger. The method () corresponds to the fallback key (in fact a presence of this method shows that this package has overloading enabled, and it is what is used by the Overloaded function of module overload ).

The module might issue the following warnings:

(W) The call to overload::constant contained an odd number of arguments. The arguments should come in pairs.

(W) You tried to overload a constant type the overload package is unaware of.

(W) The second (fourth, sixth, ...) argument of overload::constant needs to be a code reference. Either an anonymous subroutine, or a reference to a subroutine.

(W) use overload was passed an argument it did not recognize. Did you mistype an operator?

# BUGS AND PITFALLS

A pitfall when fallback is TRUE and Perl resorts to a built-in implementation of an operator is that some operators have more than one semantic, for example | :

You might expect this to output "12". In fact, it prints "<": the ASCII result of treating "|" as a bitwise string operator - that is, the result of treating the operands as the strings "4" and "8" rather than numbers. The fact that numify ( 0+ ) is implemented but stringify ( "" ) isn't makes no difference since the latter is simply autogenerated from the former.

The only way to change this is to provide your own subroutine for '|' .

Magic autogeneration increases the potential for inadvertently creating self-referential structures. Currently Perl will not free self-referential structures until cycles are explicitly broken. For example,

is asking for trouble, since

will effectively become

with the same result as

Even if no explicit assignment-variants of operators are present in the script, they may be generated by the optimizer. For example,

may be optimized to

The symbol table is filled with names looking like line-noise.

This bug was fixed in Perl 5.18, but may still trip you up if you are using older versions:

For the purpose of inheritance every overloaded package behaves as if fallback is present (possibly undefined). This may create interesting effects if some package is not overloaded, but inherits from two overloaded packages.

Before Perl 5.14, the relation between overloading and tie()ing was broken. Overloading was triggered or not based on the previous class of the tie()d variable.

This happened because the presence of overloading was checked too early, before any tie()d access was attempted. If the class of the value FETCH()ed from the tied variable does not change, a simple workaround for code that is to run on older Perl versions is to access the value (via () = $foo or some such) immediately after tie()ing, so that after this call the previous class coincides with the current one.

Barewords are not covered by overloaded string constants.

The range operator .. cannot be overloaded.

Perldoc Browser is maintained by Dan Book ( DBOOK ). Please contact him via the GitHub issue tracker or email regarding any issues with the site itself, search, or rendering of documentation.

The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the Perl issue tracker , the mailing list , or IRC to report any issues with the contents or format of the documentation.

IMAGES

  1. Perl Operator Types

    perl defined or assignment operator

  2. Perl OR

    perl defined or assignment operator

  3. Assignment Operators in C

    perl defined or assignment operator

  4. Perl Commands

    perl defined or assignment operator

  5. PPT

    perl defined or assignment operator

  6. Perl 101

    perl defined or assignment operator

VIDEO

  1. ঈদের ছুটিতে কক্সবাজারে ভ্রমণপিপাসুদের উপচে পড়া ভিড়

  2. Core

  3. How to define constant in php 2024

  4. have you used Logical Or Assignment (||=) ? #coding #javascript #tutorial #shorts

  5. How to create a new custom role in Ans?

  6. Python Vs Perl Programming

COMMENTS

  1. perlop

    These combined assignment operators can only operate on scalars, whereas the ordinary assignment operator can assign to arrays, hashes, lists and even references. ... There is no low precedence operator for defined-OR. # C Operators Missing From Perl . Here is what C has that Perl doesn't: # unary & Address-of operator. (But see the ...

  2. operators

    If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call. For example, because named unary operators have higher precedence than ||:

  3. Use the logical-or and defined-or operators to provide default

    Defined-or. Since version 5.10.0 Perl has has had the defined-or operator ('//'). This will check if the variable is defined, and if it is not, Perl will execute the code on the right-side of the operator. We can use it to simplify our subroutine code:

  4. Perl Programming/Operators

    Perl's set of operators borrows extensively from the C programming language. ... The basic assignment operator is = that sets the value on the left side to be equal to the value on the right side. It also returns the value. ... Note that the case is defined by the first operand, and that the 1..'a' and (10..-10) operations return empty list.

  5. Perl Operators

    An operator is a character that represents an action, for example + is an arithmetic operator that represents addition. Operators in perl are categorised as following types: 1) Basic Arithmetic Operators. 2) Assignment Operators. 3) Auto-increment and Auto-decrement Operators. 4) Logical Operators.

  6. Understanding the 'or' Operator in Perl: A Comprehensive Guide

    This article will explore the Perl 'or' operator in detail, providing examples and tips to help you avoid common pitfalls. Explanation of the 'or' Operator in Perl; In Perl, the 'or' operator is a logical operator that is used to perform logical OR operations. It returns true if either or both of the conditions being compared are true.

  7. Perl Operators

    Numeric operators. Perl provides numeric operators to help you operate on numbers including arithmetic, Boolean and bitwise operations. Let's examine the different kinds of operators in more detail. Arithmetic operators. Perl arithmetic operators deal with basic math such as adding, subtracting, multiplying, diving, etc. To add (+ ) or ...

  8. Operators

    Comparison or relational operators are discussed in the Conditional Decisions section of this tutorial. Please review them in that section. Assignment Operators. Used to assign scalar or array data to a data structure. Operators: = Simple assignment - assigns values from right side operands and operators to left side operand

  9. Perl Operators

    A perl operator is a series of symbols used as syntax. An operator is a sort of function and its operands are arguments. ... Conditional operators =, +=, -=, *= Assignment operators, Comma operator: not: low precedence logical NOT: and: low precedence logical AND: or, xor: ... The arity of an operator can be defined as the number of operands on ...

  10. Set default values with the defined-or operator

    That's a bit messy, so Perl 5.10 introduces the defined-or operator, //. Instead of testing for truth, it tests for defined-ness. Instead of testing for truth, it tests for defined-ness. If its lefthand value is defined, even if it's false (i.e. 0 , '0' , or the empty string), that's what it returns, short-circuiting the righthand side.

  11. variaables and related operators

    The things Perl makes available to the programmer to work with are variables. Unlike many other programming languages, Perl does not require separate declaration of variables; they are defined implicitly within expressions, such as an assignment statement. Perl provides three kinds of variables: scalars, arrays, and associative arrays. The ...

  12. Linux Perl Operators Help and Examples

    There is no low precedence operator for defined-OR. C Operators Missing From Perl. Here is what C has that Perl doesn't: unary &: Address-of operator. But see the "\" operator for taking a reference. unary *: Dereference-address operator. Perl's prefix dereferencing operators are typed: $, @, %, and &. (TYPE): Type-casting operator.

  13. perlglossary

    An operator that surrounds its operand, like the angle operator, or parentheses, or a hug. A user-defined type, implemented in Perl via a package that provides (either directly or by inheritance) methods (that is, subroutines) to handle instances of the class (its objects ). See also inheritance.

  14. Perl Bitwise OR and assignment operator

    The Bitwise OR and assignment operator (|=) assigns the first operand a value equal to the result of Bitwise OR operation of two operands. The Bitwise OR operator (|) is a binary operator which takes two bit patterns of equal length and performs the logical OR operation on each pair of corresponding bits. It returns 1 if either or both bits at ...

  15. perl

    Stack Overflow Public questions & answers; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Talent Build your employer brand ; Advertising Reach developers & technologists worldwide; Labs The future of collective knowledge sharing; About the company

  16. Assignment Operators

    Assignment Operators. Get introduced to the functionality of the assignment and the combined assignment operator in this lesson. We'll cover the following. Basic assignment. Example. Explanation. Combined assignment. Example. Difference between = and == operator.

  17. What is the use of '||=' assignment operator in perl scripting?

    Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

  18. Perl Operator: A Comprehensive Guide

    Assignment Operators . Assignment operators in programming languages like Perl are fundamental components that simplify assigning values to variables. They are not just limited to the basic assignment but also include a range of compound assignment operators that combine arithmetic, string, and other operations with the assignment.

  19. Learn Perl Assignment operators tutorial and examples

    Learn Perl Assignment operator with code examples. w3schools is a free tutorial to learn web development. It's short (just as long as a 50 page book), simple (for everyone: beginners, designers, developers), and free (as in 'free beer' and 'free speech'). It consists of 50 lessons across 4 chapters, covering the Web, HTML5, CSS3, and Sass.

  20. overload

    The subroutine for '=' does not overload the Perl assignment operator: it is used only to allow mutators to work as described here. (See "Assignments" above.) As for other operations, the subroutine implementing '=' is passed three arguments, though the last two are always undef and '' .

  21. How does the assignment operator (=) in Perl work internally?

    @Praveenkumar It is only a way to open a file and make $. defined. You'll notice that I also added a file name to the end. You'll notice that I also added a file name to the end. - TLP