in reply to Perl Syntax/resources that we generally don't know or forget.

Lvalue substr() is my special friend. Did you know you can bind regular expressions and transliterations to them?

my $x = "x" x 50; substr($x, 12, 34) =~ tr[x][y];

Foreach's iterator variable is an alias for an item in the list being iterated through. This works with values() and hash slices, too.

my %x = (a=>1, b=>2, c=>3); $_ *= 2 foreach values %x;

I'm so, so easily amused. :)

-- Rocco Caputo - rcaputo@pobox.com - poe.perl.org

Replies are listed 'Best First'.
•Re: Re: Perl Syntax that we generally don't know or forget.
by merlyn (Sage) on Jan 18, 2004 at 13:13 UTC
    No! Don't stop there! You can also use the lvalue bindings of argument passing! Three nested lvalue usages:
    my $value = "abcde"; sub attack { $_[0] = "x" } attack($_) for substr($value, 2, 1); print "$value\n"; # prints "abxde\n"
    And if I understood lvalue subroutines better, I could probably write "attack($_) = 'x'" instead, for a fourth layer. {grin}

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      Like this?. Or is there something I'm missing here..
      sub attack :lvalue { substr($_[0], 2, 1) ; }

      -Lee

      "To be civilized is to deny one's nature."
        That is supposed to work, but currently has some problems (see perl bug #24200) if you call attack in an rvalue context after calling it in an lvalue context.
substr() as an lvalue
by ambrus (Abbot) on Jan 19, 2004 at 11:37 UTC

    Wow, I didn't know that. You can even $a="abcdef"; substr($a,2,-2) x= 3; print $a,$/; that prints abcdcdcdef. This is amazing.

    And you can buy 2 cats as simple as: $_="I have 2 dogs and 9 cats.\n"; /(\d+)\s+cat/ or die; substr($_,$-[1],$+[1]-$-[1])+= 2; print; which prints `I have 2 dogs and 11 cats.'.

    See also Re: cut of first char of a string.