← Back to Perl Course | Chapter 2: Variables | Lesson 6 of 7

Context को समझें

Same expression आप इसे कहाँ इस्तेमाल करते हैं इसके आधार पर एक list या एक single value दे सकता है।

In this page:

  1. Context

Context

Perl में scalar context और list context है, और कई operations हर एक में अलग behave करते हैं। Scalar context में एक array इसके elements की संख्या return करता है, जबकि list context में यह सब return करता है। आप scalar() से scalar context force कर सकते हैं, और parentheses में एक list को assign करना list context देता है।

Note: my ($first) = @array पहला element लेता है, लेकिन my $count = @array count लेता है।

उदाहरण: Context

perl
use strict;
use warnings;

my @colors = qw(red green blue);

my $count = @colors;
my ($first) = @colors;
my $last_index = $#colors;
print "count=$count first=$first last_index=$last_index\n";
print "Colors: " . @colors . "\n";
print "Colors: @colors\n";
print "scalar reverse: ", scalar reverse("abc", "def"), "\n";
print "list reverse: ", join(",", reverse("abc", "def")), "\n";
my $matches = () = "banana" =~ /a/g;
print "number of a's: $matches\n";

# Output:
# count=3 first=red last_index=2
# Colors: 3
# Colors: red green blue
# scalar reverse: fedcba
# list reverse: def,abc
# number of a's: 3
{# 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. my ($x) = @a लिखना और array length की उम्मीद करना
  2. scalar context में एक array print करना जब आपको इसके elements चाहिए
  3. यह realize न करना कि reverse scalar context में अलग behave करता है
चैप्टर सारांश
  • Scalar context एक value चाहता है
  • List context कई values चाहता है
  • Scalar context में एक array इसकी length है
  • Left side पर parentheses list assignment देते हैं
🔒

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.