Perl can use a scalar as text in one expression and as a number in another.

context Context is how Perl decides whether a value should be treated as text, a number, or a list.

Numeric Context

raw
numeric_context.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;

my $raw = "12";
my $doubled = $raw * 2;
my $text_code = $raw . "0";

print "raw=$raw\n";
print "doubled=$doubled\n";
print "text_code=$text_code\n";
use strict;
use warnings;

my $raw = "7";
my $doubled = $raw * 2;
my $text_code = $raw . "0";

print "raw=$raw\n";
print "doubled=$doubled\n";
print "text_code=$text_code\n";
use strict;
use warnings;

my $raw = "42";
my $doubled = $raw * 2;
my $text_code = $raw . "0";

print "raw=$raw\n";
print "doubled=$doubled\n";
print "text_code=$text_code\n";
  1. $raw ← 12, $doubled ← 24, $text_code ← 120

    4my $raw→ 12 = "12"; #@raw="7", "42"5my $doubled→ 24 = $raw12 * 2;6my $text_code→ 120 = $raw12 . "0";78print "raw=$raw12\n";9print "doubled=$doubled24\n";10print "text_code=$text_code120\n";
    outputraw=12
    doubled=24
    text_code=120
  1. $raw ← 7, $doubled ← 14, $text_code ← 70

    4my $raw→ 7 = "7";5my $doubled→ 14 = $raw7 * 2;6my $text_code→ 70 = $raw7 . "0";78print "raw=$raw7\n";9print "doubled=$doubled14\n";10print "text_code=$text_code70\n";
    outputraw=7
    doubled=14
    text_code=70
  1. $raw ← 42, $doubled ← 84, $text_code ← 420

    4my $raw→ 42 = "42";5my $doubled→ 84 = $raw42 * 2;6my $text_code→ 420 = $raw42 . "0";78print "raw=$raw42\n";9print "doubled=$doubled84\n";10print "text_code=$text_code420\n";
    outputraw=42
    doubled=84
    text_code=420

Follow the Context

  1. $raw starts as 12.
  2. $doubled = $raw * 2 treats it as a number.
  3. $doubled becomes 24.
  4. $text_code = $raw . "0" treats it as text.
  5. The program prints raw=12, doubled=24, and text_code=120. | raw | doubled | text_code | | --- | --- | --- | | 7 | 14 | 70 | | 12 | 24 | 120 | | 42 | 84 | 420 |

Exercise: numeric_context.pl

Reproduce doubled=24 and text_code=120, then use raw values 7 and 42 to predict both results.