當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。