Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I need to split a string three times with differents PATTERNS and I'm reusing variable $fields[]. It seem to work fine surprisingly to me.
Is Perl storing the string to split on a buffer so you can reuse storaging space?
@fields = split /\s/; @fields = split /\(/, $fields[$#fields]; @fields = split /,/, $fields[1];
Thank you and sorry for my english

20041111 Janitored by Corion: Fixed code tag

Replies are listed 'Best First'.
Re: reuse of split variable?
by davido (Cardinal) on Nov 11, 2004 at 18:43 UTC

    In each case, the computation on the right-hand-side of the '=' operator is completed in its entirety before it is assigned to @fields.

    You can see a similar concept at work in this very common expression:

    my $value = 10; $value = $value + 1; print $value, $/;

    In this example, $value + 1 is evaluated first, and the result is assigned to $value


    Dave

      Thank you for your answer.
      I'm used to C and sometimes you cannot work on a variable space ans storing results to it at the same time.

      Advantages of Perl
        True in perl also, but only in nooks and crannies. Compare these three:
        $ perl -we'@foo = 1..10; for (@foo) { delete $foo[10-$_] } print scala +r @foo' 5 $ perl -we'@foo = 1..10; for (my @bar=@foo) { delete $foo[10-$_] } pri +nt scalar @foo' 0 $ perl -we'@foo = 1..10; for (@foo,()) { delete $foo[10-$_] } print sc +alar @foo' Use of freed value in iteration at -e line 1.
Re: reuse of split variable?
by pg (Canon) on Nov 11, 2004 at 20:33 UTC
    "Is Perl storing the string to split on a buffer so you can reuse storaging space? "

    Don't feel this question is related to the fact you can reusing @fields.

    You can store the returned result from split in @fields any time you want, as many times as you want. Nothing different from c.

    The string that split works on is passed in as parameter, is it not the same thing in c? BTW as it is not passed in as ref (or pointer as in c), once you passed it in, the copy inside the sub has nothing to do with the oringinal string from where split copied its value.

    From a c programmer's point of view, the only thing might surprise you is the fact that @fields is growing on its own without you explicitly allocate memory for it.

Re: reuse of split variable?
by PerlingTheUK (Hermit) on Nov 11, 2004 at 23:28 UTC
    My Regexp knowlege is yucks, but i am wondering if you really need to do this three times or if a single split with a clever regexp does the job.
    If I get it right, something like
    @fields = split /\s|\(|,/;
    would work if , and ( are only once in your string.

    Cheers,
    PerlingTheUK
Re: reuse of split variable?
by TedPride (Priest) on Nov 12, 2004 at 08:07 UTC
    What he wants is something more like:
    m/\s.*\((.*)$/; @fields = split(/,/, $1);
    I don't see a good way to put it into one statement.