- Perl ›
- Operators ›
- Arithmetic operator ›
- here
Increment operator "++"
Using the increment operator , assigned to variable You can add 1 to the number. The increment operator can be added before or after the variable.
# Increment (postfix) $num ++; # Increment (prefix) ++ $num;
The increment operator has the same meaning as the following description using addition operator.
$num = $num + 1;
The increment operator is often used in for statement.
for (my $i = 0; $i < 10; $i++) { print "$i\n"; }
This example program outputs 0 to 10.
Difference between prefix increment and suffix increment
Prefix increments and postfix increments have the same meaning when used alone, but have different meanings when a return value is used, such as being assigned.
Prefix increment
For prefix increments, the incremented value is returned.
my $num1 = 0; my $num2 = ++ $num;
"$Num1" is incremented to 1. This value of 1 is returned and assigned to "$num2".
I explained in the case of assignment, but I will also give an example of passing a value to subroutine. The fun is passed a incremented value .
func (++ $i);
Postfix increment
For prefix increments, the value before the increment is returned.
my $num1 = 0; my $num2 = $i++;
"$Num1" is incremented to 1, but the value before the increment, 0, is assigned to $num2.
The above two have different values in $k. In the first case, $k contains 1. In the second case, $k will be 0.
I explained in the case of assignment, but I will also give an example of passing a value to a subroutine. The fun is passed the value before it was incremented .
func ($i++);
Decrement operator
The decrement operator is the opposite of the increment operator, which allows you to subtract 1. The decrement operator is explained in detail below.