A source filter implementation of with found in other languages, where the given argument becomes a topicalizer for the given block, or if it's a bareword the block will be in the bareword's namespace e.g
use With; my $foo = "a string"; print "before with: $foo\n"; with($foo) { s/a /not a /; } print "after with: $foo\n"; with(foo) { sub new { bless {}, shift; } } print foo->new; __output__ before with: a string after with: not a string foo=HASH(0x80fbbf0)
Disclaimer: the above code was inspired by a CB conversation
package With; use strict; use Regexp::Common; use Filter::Simple; FILTER_ONLY code => sub { s[ with \s* ( $RE{balanced}{-parens => '()'} ) \s* { ] < my($t) = $1 =~ /\((.*)\)/; $t =~ /^[_a-zA-Z](?:(?:\w*)(?:(?:'|::)(?:\w+)+)?)*\z/ ? "{ package $t;" : "for($t) {" >iexsg; }, ; q{ they think it's all over, and now it is };

Replies are listed 'Best First'.
Re: a 'with' statement for perl
by mirod (Canon) on Apr 25, 2003 at 11:59 UTC

    It seems to me that the first part, using with to topicalize is exactly what for does:

    #!/usr/bin/perl -w use strict; my $foo = "a string"; print "before with: $foo\n"; for($foo) { s/a /not a /; } print "after with: $foo\n";

    I believe that's indeed one of the reasons for the use of for as a keyword, instead or just foreach.

      It seems to me that the first part, using with to topicalize is exactly what for does ...
      It is indeed, but for's behaviour isn't obvious to many programmers coming from other languages (and yes, I know it's clearly documented in perlsyn). I should possibly also mention in the description that it was inspired out of a CB conversation, which explains away the obvious redundancy ;)
      HTH

      _________
      broquaint

Re: a 'with' statement for perl
by demerphq (Chancellor) on Apr 26, 2003 at 15:48 UTC

    Heh. I had the strangest feeling of deja-vu when I read this node. lol.


    ---
    demerphq

    <Elian> And I do take a kind of perverse pleasure in having an OO assembly language...