in reply to foreach (each character in string..)?

A couple other ways that don't make an arrayconstruct a list in memory of all the characters:
for my $i (0..length($string)-1) { # whatever with substr($string, $i, 1) }
or
while ($string =~ /./gs) { # whatever with $& # note that this incurs the penalty for using $& }

The PerlMonk tr/// Advocate

Replies are listed 'Best First'.
Re: Re: foreach (each character in string..)?
by Aragorn (Curate) on Jan 20, 2004 at 21:14 UTC
    while ($string =~ /./gs) {
        # whatever with $&
        # note that this incurs the penalty for using $&
    }
    
    You can avoid the $& penalty by using parentheses: /(.)/gs and using the $1 variable.

    Arjen

      You can avoid the $& penalty by using parentheses: /(.)/gs and using the $1 variable.

      Just to clarify ... you can avoid the $& penalty on all your other regular expressions, but you still pay it on this one (only its name is changed to $1)

Re: Re: foreach (each character in string..)?
by revdiablo (Prior) on Jan 20, 2004 at 20:20 UTC

    I tried to send you a /msg, but I am unsure how to do so due to the space in your username. I have a quick pedantic note: you should probably s/array/list/ on your first sentence. 8^)

    Even more pedantic is to point out that 0..length($string)-1 does indeed make a list, but I think we know what you meant. ;)

    Update: I stand corrected. It might be noted that I knew there was an optimization with for and the range operator, but I thought it still ended up building a list -- I didn't realize it just turned into an iterator.

      Yes, I am a bit loose in calling lists arrays. But note that in a foreach, the .. operator with integer operands does NOT create a list. It acts as an iterator. This is a special optimization introduced in 5.005.

      The PerlMonk tr/// Advocate