This article focuses on how to remove a value from an array in Perl? This article explains how to assign the elements of an array to undef, and then delete the elements from the array, and the friends you need can refer to the
I'm not sure if undef has a definite relationship with the elimination of values from the array, guess what, if we treat undef as "empty," there will be some connection. But generally, assigning something to undef and deleting something is different.
First look at how to assign the elements of an array to undef, and then learn how to remove elements from the array.
Start with the following code:
The code is as follows:
Use Data::D umper qw (dumper);
My @dwarfs = QW (Doc grumpy Happy sleepy Sneezy Dopey);
Print dumper @dwarfs;
When you print with data::D Umper, you get the following output:
The code is as follows:
$VAR 1 = [
' Doc ',
' Grumpy ',
' Happy ',
' Sleepy ',
' Sneezy ',
' Dopey ',
' Bashful '
];
Assign an element to undef
Use the return value of the undef () function:
The code is as follows:
Use Data::D umper qw (dumper);
My @dwarfs = QW (Doc grumpy Happy sleepy Sneezy Dopey);
$dwarfs [3] = undef;
Print dumper @dwarfs;
The code assigns the number 3rd element (the 4th element in the array) to undef, but does not change the size of the array:
The code is as follows:
$VAR 1 = [
' Doc ',
' Grumpy ',
' Happy ',
Undef
' Sneezy ',
' Dopey ',
' Bashful '
];
Using the undef () function for an element of a direct array also produces the same result:
The code is as follows:
Use Data::D umper qw (dumper);
My @dwarfs = QW (Doc grumpy Happy sleepy Sneezy Dopey);
Undef $dwarfs [3];
Print dumper @dwarfs;
Therefore, $dwarfs [3] = undef; and undef $dwarfs [3]; the function is the same, they can assign the value to undef.
To remove an element from an array using splice
The splice function removes the element from the array completely:
The code is as follows:
Use Data::D umper qw (dumper);
My @dwarfs = QW (Doc grumpy Happy sleepy Sneezy Dopey);
Splice @dwarfs, 3, 1;
Print dumper @dwarfs;
$VAR 1 = [
' Doc ',
' Grumpy ',
' Happy ',
' Sneezy ',
' Dopey ',
' Bashful '
];
As you can see in this example, the array shortens a unit because we remove an element from the middle of the array.
This is how to remove an element from the array.