How to delete a value from an array in Perl
This article mainly introduces how to delete a value from an array in Perl? This article explains how to assign an array element to undef and then delete the element from the array. For more information, see
I'm not sure whether undef has a definite relationship with the value removed from the array. I guess if we think of undef as "null", there will be some connections. But in general, assigning something to undef is different from deleting something.
First, let's take a look at how to assign an array element to undef, and then learn how to delete elements from the array.
Start with the following code:
The Code is as follows:
Use Data: Dumper qw (Dumper );
My @ dwarfs = qw (Doc Grumpy Happy Sleepy Sneezy Dopey Bashful );
Print Dumper \ @ dwarfs;
When Data: Dumper is used for printing, the following output is obtained:
The Code is as follows:
$ VAR1 = [
'Doc ',
'Grumpy ',
'Happy ',
'Sleepy ',
'Sneezy ',
'Dopey ',
'Bashfu'
];
Assign an element to undef
Return Value of the undef () function:
The Code is as follows:
Use Data: Dumper qw (Dumper );
My @ dwarfs = qw (Doc Grumpy Happy Sleepy Sneezy Dopey Bashful );
$ Dwarfs [3] = undef;
Print Dumper \ @ dwarfs;
The code will assign element 3 (element 4th in the array) to undef, but does not change the array size:
The Code is as follows:
$ VAR1 = [
'Doc ',
'Grumpy ',
'Happy ',
Undef,
'Sneezy ',
'Dopey ',
'Bashfu'
];
Using the undef () function for an element of the array directly produces the same result:
The Code is as follows:
Use Data: Dumper qw (Dumper );
My @ dwarfs = qw (Doc Grumpy Happy Sleepy Sneezy Dopey Bashful );
Undef $ dwarfs [3];
Print Dumper \ @ dwarfs;
Therefore, $ dwarfs [3] = undef; and undef $ dwarfs [3]; have the same effect. Both of them can assign the value to undef.
Use splice to remove elements from the array
The splice function permanently deletes elements from the array:
The Code is as follows:
Use Data: Dumper qw (Dumper );
My @ dwarfs = qw (Doc Grumpy Happy Sleepy Sneezy Dopey Bashful );
Splice @ dwarfs, 3, 1;
Print Dumper \ @ dwarfs;
$ VAR1 = [
'Doc ',
'Grumpy ',
'Happy ',
'Sneezy ',
'Dopey ',
'Bashfu'
];
In this example, an array is reduced by a unit because an element is removed from the array.
This is how to delete an element from the array.