Thu, 25 Sep 2008

Contexts


Permanent link

NAME

"Perl 5 to 6" Lesson 06 - Contexts

LAST UPDATED

2015-02-25

SYNOPSIS

    my @a = <a b c>;
    my $x = @a;
    say $x[2];          # c
    say (~2).WHAT;      # (Str)
    say +@a;            # 3
    if @a < 10 { say "short array"; }

DESCRIPTION

When you write something like this

    $x = @a

in Perl 5, $x contains less information than @a - it contains only the number of items in @a. To preserve all information, you have to explicitly take a reference: $x = \@a.

In Perl 6 it's the other way round: by default you don't lose anything, the scalar just stores the array. This was made possible by introducing a generic item context (called scalar in Perl 5) and more specialized numeric, integer and string contexts. Void and List context remain unchanged, though void context is now called sink context.

You can force contexts with special syntax.

    syntax       context

    ~stuff       String
    ?stuff       Bool (logical)
    +stuff       Numeric
    -stuff       Numeric (also negates)
    $( stuff )   Generic item context
    @( stuff )   List context
    %( stuff )   Hash context

Flattening

In Perl 5, list context always flattens out arrays (but not array references).

In Perl 6, this is not always the case, and depends on the context:

    my @a = 1, 2;
    my @b = 3, 4, 5;
    my @c = @a, @b;     # preserves structure
    say @c.perl;        # [[1, 2], [3, 4, 5]]
    
    @c = flat @a, @b;
    say @c.perl;        # [1, 2, 3, 4, 5]

You can force flattening list context yourself by using *@a in a signature:

    sub flat-elems(*@a) {
        return @a.elems
    };
    say flat-elems(@a, @b);     # 5

MOTIVATION

More specific contexts are a way to delay design choices. For example it seems premature to decide what a list should return in scalar context - a reference to the list would preserve all information, but isn't very useful in numeric comparisons. On the other hand a string representation might be most useful for debugging purposes. So every possible choice disappoints somebody.

With more specific context you don't need to make this choice - it returns some sensible default, and all operators that don't like this choice can simply evaluate the object a more specific context.

For some things (like the Match object), the different contexts really enhance their usefulness and beauty.

SEE ALSO

http://design.perl6.org/S02.html#Context http://perlgeek.de/blog-en/perl-6/immutable-sigils-and-context.html

[/perl-5-to-6] Permanent link