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

Hi all, Does $- exist in perl? Basically the following code works, but if i replace $- with $_, i dont get what i expect.
while (<IN>) { push @new, $_ =~ m/^\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+.*/; $num =scalar$#new; print "\n$num\n"; } while (<REPLACE>) { $- =~ s/^\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+(\s+.*)/$new[$i++] $1/; print OUT $_; }

Replies are listed 'Best First'.
Re: $- ??
by davido (Cardinal) on Sep 26, 2004 at 16:37 UTC

    From perldoc perlvar:

    $-
    The number of lines left on the page of the currently selected output channel. Used with formats. (Mnemonic: lines_on_page - lines_printed.)

    Punctuation variables are reserved for special purposes in Perl. Also, your second while loop is populating $_, not $-. So if you want the contents of <REPLACE> to be passed through that second substitution operator, you should bind $_ to it, not $-.

    See also perldoc perlvar:

    $_
    The default input and pattern-searching space.

    It has a special purpose. You used it correctly in the first while statement, but incorrectly in the second while.


    Dave

Re: $- ??
by Zed_Lopez (Chaplain) on Sep 26, 2004 at 16:40 UTC

    perlvar

    $FORMAT_LINES_LEFT
    $-
    The number of lines left on the page of the currently selected output channel. Used with formats. (Mnemonic: lines_on_page - lines_printed.)

    Perl has lots of these special variables. They're independent of each other (though some have related areas of utility.) In the general case, arbitrarily substituting one for another is the wrong thing, and you should expect it to break your code.

Re: $- ??
by ikegami (Patriarch) on Sep 26, 2004 at 18:35 UTC

    It should be $_ like the others explained. Let's look at why it doesn't work with $_. (I don't see how it would work with $- any better.) You're missing parens in your first match. m// returns 1 or undef/() if you have no captures.

    { my @new; $_ = 'bla'; push @new, $_ =~ m/^bla/; print(@new, "\n"); # prints 1 } { my @new; $_ = 'bla'; push @new, $_ =~ m/^(bla)/; print(@new, "\n"); # prints bla }

    $_ =~ is redundant and can simply be ommited. Also, s/...(.*)/...$1/ is the same as s/.../.../. The final product is:

    while (<IN>) { push @new, m/^(\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+)/; print "\n$#num\n"; } while (<REPLACE>) { s/^\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+/$new[$i++]/; print OUT $_; }