当前位置: 首页>>代码示例>>用法及示例精选>>正文


Perl delete()用法及代码示例

Perl中的Delete()用于从哈希中删除指定的键及其关联的值,或者在数组的情况下删除指定的元素。此操作仅适用于单个元素或切片。

用法: delete(LIST)

参数:
LIST将被删除


返回值:
如果该键不存在,则返回undef,否则返回与已删除键关联的值

示例1:在哈希上实现delete()

#!/usr/bin/perl 
  
# Initializing hash  
%hash1 = ('Geeks' => 45, 'for' => 30, 'Now' => 40);  
  
# To delete the List passed as parameter 
$deleted_element = delete($hash1{'for'}); 
  
# Printing elements of Hash  
print "$hash1{'Geeks'}\n";  
print "$hash1{'for'}\n";  
print "$hash1{'Now'}\n";  
  
# Printing the deleted element 
print "Deleted element: $deleted_element";

输出:

45

40
Deleted element: 30

示例2:在阵列上实现delete()

#!/usr/bin/perl 
  
# Initializing array 
@array1 = (10, 20, 30, 40, 50, 60);  
  
# To delete the array element at index 2 
$deleted_element = delete(@array1[2]); 
  
# Printing elements of Array  
print "Updated Array: @array1"; 
  
# Printing the deleted element 
print "\nDeleted element: $deleted_element";

输出:

Updated Array: 10 20  40 50 60
Deleted element: 30


相关用法

注:本文由纯净天空筛选整理自Code_Mech大神的英文原创作品 Perl | delete() Function。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。