The operator ++ in Perl

The double plus operator is used in Perl to increase the value of a variable by one.

Example:

▶ Run
#!/usr/bin/perl

my $i = 100;

$i++;

print $i;

The program will display the number 101.

The entry form

There are two forms of recording: you can specify the operator after the variable (Postfix notation) or before the variable (prefix notation):

$i++;
++$i;

If the command is on one line, there is no difference between prefix and Postfix notation of. There is a difference only if the operator ++ is used as part of a team. If ++ is located in front of the variable the value of the variable will increase before executing the remaining commands. If ++ is after the variable, then the value of the variable will increase after executing the remaining commands.

Here is an example.

This program displays the number 100 and 101:

▶ Run
#!/usr/bin/perl

use feature qw(say);

my $i = 100;

say $i++;
say $i;

But this program displays the number 101 two times:

▶ Run
#!/usr/bin/perl

use feature qw(say);

my $i = 100;

say ++$i;
say $i;

++ for rows

The operator ++ has a special magic. It acts in a special way if it is applied to a variable which is a string.

And it is interesting that the operator -- so there's no magic.

Example. This program will display the string a2:

▶ Run
#!/usr/bin/perl

my $str = 'a1';

$str++;

print $str;

Here are some examples which will make the operator ++ with the string in a variable:

'a' -> 'b'
'b' -> 'c'
'z' -> 'aa'
'aa' -> 'ab'
'az' -> 'ba'
'zz' -> 'aaa'

'A1' -> 'A2'
'A9' -> 'B0'

'undef' -> 'undeg'

'A+100' -> '1'

When you use the operator ++ with strings there are a lot of subtleties. It is best not to apply to the rows. If you use for row operations, you have a very good understanding of how it works or there are errors. But it is possible that people after which you will have to work with this code not so well understand how a ++ for strings and when you change the code to add bugs.

Misuse

The operator ++ can only be used for variables. If you try to use ++ not for the variable, and the primes, it will generate an error. Here is an example of code with error:

▶ Run
#!/usr/bin/perl

my $i = 100++; # error!

When you run this program it will error:

Can't modify constant item in postincrement (++) at script.pl line 3, near "100++"
Execution of script.pl aborted due to compilation errors.

Similarly, it cannot be applied to arrays:

▶ Run
#!/usr/bin/perl

my @arr = (1, 2, 3);

@arr++; # error
Can't modify private array in postincrement (++) at script.pl line 5, near "@arr++"
Execution of script.pl aborted due to compilation errors.

And hashes:

▶ Run
#!/usr/bin/perl

my %h = (
    a => 1,
);

%h++; # error
Can't modify private hash in postincrement (++) at script.pl line 7, near "%h++"
Execution of script.pl aborted due to compilation errors.

Other articles

Comments