How to delete a value from an array in Perl?

I'm not sure if undef has exactly anything to do with eliminating values ​​from an array, guessing there is some connection if we consider undef to be "empty". But in general, assigning something to undef is not the same as deleting something.

Let's first look at how to assign the elements of the array to undef, and then learn how to delete elements from the array.

Start with the code below:

The copy code code is as follows:


use Data::Dumper qw(Dumper);
my @dwarfs = qw(Doc Grumpy Happy Sleepy Sneezy Dopey Bashful);
print Dumper \@dwarfs;


When printing using Data::Dumper, the following output is obtained:

The copy code code is as follows:


$VAR1 = [
          'Doc',
          'Grumpy',
          'Happy',
          'Sleepy',
          'Sneezy',
          'Dopey',
          'Bashful'
        ];


Assign element to undef

Use the return value of the undef() function:

The copy code 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;


These codes will set element 3 (the 4th element in the array) to undef, but will not change the size of the array:

The copy code code is as follows:


$VAR1 = [
          'Doc',
          'Grumpy',
          'Happy',
          undef,
          'Sneezy',
          'Dopey',
          'Bashful'
        ];


Using the undef() function directly on an element of the array will also produce the same result:

The copy code 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, they can both assign the value to undef.

Removing elements from an array using splice
The splice function completely removes elements from the array:

The copy code 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',
          'Bashful'
        ];


You can see that in this example the array is shortened by one unit because we removed one element from the middle of the array.

This is how to remove an element from an array.

おすすめ

転載: blog.csdn.net/jh035512/article/details/128141752