The operator -- in Perl

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

Example:

▶ Run
#!/usr/bin/perl

my $i = 100;

$i--;

print $i;

The program will display the number 99.

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 99:

▶ Run
#!/usr/bin/perl

use feature qw(say);

my $i = 100;

say $i--;
say $i;

But this program will display the number 99 twice:

▶ Run
#!/usr/bin/perl

use feature qw(say);

my $i = 100;

say --$i;
say $i;

-- for rows

Have operator ++ there is a special magic when it is applied to a variable which is a string.

The operator -- so there's no magic. The string is coerced into a number and from this number subtract one.

Here is an example. The program displays the number -1

▶ 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' -> -1
'100ABC' -> 99
'0100ABC' -> 99

Misuse

The operator -- can only be used for variables. If you try to use -- is not variable, and for a simple number, 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 postdecrement (--) 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 postdecrement (--) 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 postdecrement (--) at script.pl line 7, near "%h--"
Execution of script.pl aborted due to compilation errors.

Other articles

Comments