← Back to Perl Course | Chapter 8: Modules | Lesson 2 of 7

List::Util का उपयोग

List::Util lists के साथ काम करने के लिए sum, max, first, और reduce जैसे fast helpers देता है।

In this page:

  1. List::Util

List::Util

List::Util एक core module है जिसके functions C में लिखे हैं और नाम से import होते हैं। sum, min, max, और product एक list को एक number में reduce करते हैं, first उस पहले element को return करता है जिसके लिए एक block true हो, और reduce $a और $b इस्तेमाल करते हुए एक block से एक list combine करता है। uniq duplicates के बिना elements return करता है, और shuffle इन्हें random order में mix करता है।

Note: sum और max एक empty list के लिए undef return करते हैं, इसलिए जब list empty हो सकती है इसके against guard करें।

उदाहरण: List::Util

perl
use strict;
use warnings;
use List::Util qw(sum min max product first reduce uniq);

my @nums = (4, 8, 15, 16, 23, 42);
print "sum: ", sum(@nums), "\n";
print "min: ", min(@nums), " max: ", max(@nums), "\n";
print "product of 1..5: ", product(1 .. 5), "\n";
my $big = first { $_ > 10 } @nums;
print "first over 10: $big\n";
my $longest = reduce { length($a) >= length($b) ? $a : $b } qw(pear banana fig apple);
print "longest word: $longest\n";
print "unique: ", join(" ", uniq(1, 1, 2, 3, 3, 3)), "\n";
my $empty = sum();
print "sum of nothing: ", defined $empty ? $empty : "undef", "\n";

# Output:
# sum: 108
# min: 4 max: 42
# product of 1..5: 120
# first over 10: 15
# longest word: banana
# unique: 1 2 3
# sum of nothing: undef
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. function names import करना भूल जाना
  2. reduce के अंदर $a और $b की बजाय $_ इस्तेमाल करना
  3. यह उम्मीद करना कि first element की बजाय इसका index return करेगा
चैप्टर सारांश
  • sum, min, max, और product numbers combine करते हैं
  • first पहला matching element ढूंढता है
  • reduce $a और $b इस्तेमाल करके एक list fold करता है
  • uniq duplicates remove करता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.