Lesson 36 of 55
9 mins readPython Context Sensitivity: Scalar, List & wantarray
In Plain English
Perl expressions behave differently depending on whether they are evaluated in Scalar context or List context. Subroutines detect caller context with the `wantarray` built-in.
Deep Dive: How It Works
Scalar Context: Expects a single value (e.g., `my $x = ...;`). An array in scalar context returns its size.
List Context: Expects a list of values (e.g., `my @items = ...;`, `my ($a, $b) = ...;`).
wantarray Built-in: Returns `1` in list context, `0` in scalar context, and `undef` in void context.
Core Rules to Remember

Context Dictates Meaning: The same expression behaves differently depending on the surrounding context.

wantarray Adapter: Allows a subroutine to return a count in scalar context and an array in list context.
Live Interactive Example
Hit Run Code to see it liveUsing wantarray for Adaptive Subroutines
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Output Console
Click "Run Code" to view the rendered output.
How it works: wantarray returned the array when assigned to @user_list and the count for $user_count.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Test Scalar Context of Array
Declare `my @items = qw(red green blue);`
Assign to scalar `my $len = @items;`
Print `"Array evaluated in scalar context: $len\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.