in reply to A TRUE-once variable

Perl doesn't have a "true-once" variable, however there are many ways to get the behaviour you want --- and several have been mentioned, including the most pertinent one: namely that an algorithm with join is probably your best option.

That said, there are a few ways to get the 'once-only' behaviour you are looking in your case without creating new synthetic variables. First you can use the flip-flop operator:

#!/usr/bin/perl -w use strict; while(<DATA>){ chomp; print ",\n" unless 1..1; print; } __DATA__ foo bar blah

In scalar context the range .. op is the flip-flop, and when using constant expressions on either side, they are automatically compared to the builtin $. variable. So the above flip-flop is only true for the first record read. This of course leads to the more explicit and only slightly longer direct comparison with $. itself:

#!/usr/bin/perl -w use strict; while(<DATA>){ chomp; print ",\n" unless $. == 1; print; } __DATA__ foo bar blah

But the idea of "once-only" can also be expressed by using the special ?? delimiters for a regex: with such delimiters, the regex will match only once --- so, using an expression that will succeed will also get you what you want:

#!/usr/bin/perl -w use strict; while(<DATA>){ chomp; print ",\n" unless ?^?; print; } __DATA__ foo bar blah

Replies are listed 'Best First'.
Re: Re: A TRUE-once variable
by Anonymous Monk on Jan 29, 2002 at 05:25 UTC
    In my opinion the ?^? trick is a bit too much of... a trick.

    First of all, one should always do reset() after a use of ??. But the status of ?? is package scoped, so you might get scary side-effects if you use a function that uses ?? inside a loop where you used the first ??.

    For instance, say that you modify your last snippet:
    sub prettify { # Just code that uses ??. } while(<DATA>){ chomp; print ",\n" unless ?^?; print prettify($_); } __DATA__ foo bar blah
    Evil indeed.

    This is the same problem as with not localized usage of $_, e.g. when people do while (<FOO>) {} without an explicit local() on $_. (I know no way to localize the status of ??.)

    -Anomo