[Israel.pm] perl -i -pe question

sawyer x xsawyerx at gmail.com
Mon Feb 20 02:26:14 PST 2012


Oh, I didn't notice the $a=1.

This is what it looked before the BEGIN{}:
BEGIN { $^I = ""; }
LINE: while (defined($_ = <ARGV>)) {
    ++$a if s/a/$a a/;
}
continue {
    die "-p destination: $!\n" unless print $_;
}

This is what it looked after:
BEGIN { $^I = ""; }
sub BEGIN {
    $a = 1;
}
LINE: while (defined($_ = <ARGV>)) {
    ++$a if s/a/$a a/;
}
continue {
    die "-p destination: $!\n" unless print $_;
}

And, in case you're wondering, you can write BEGIN as "sub BEGIN {}" but
it's not advised to do so. Apparently when you define it, it *is* what the
perl interpreter does. Odd..

On Mon, Feb 20, 2012 at 12:14 PM, Avishalom Shalit <avishalom at gmail.com>wrote:

> $ head tst
> a
> b
> c
> d
> e
> a
> b
> c
> d
> e
>
> $ perl -i -pne 'BEGIN{$a=1}$a++ if (s/a/$a a/)' tst
>
> $ head tst
> 1 a
> b
> c
> d
> e
> 2 a
> b
> c
> d
> e
>
>
> when you have a -n
> it takes the whole block and puts it inside
> while(<>){
> #code goes here
> }
>
> what happened was that $a=1. was done every line.
>
> BEGIN{}
> goes before the while.
> -a
> does a @F=split
>
> in the first line.
>
> ----
> p.s. remember that $a is magic , sort{$a<=>$b} works in strict because $a
> is already declared. so you may want to use another name. $c is good
>
> -- vish
>
>
>
>
> On 20 February 2012 09:17, sawyer x <xsawyerx at gmail.com> wrote:
>
>>
>> On Mon, Feb 20, 2012 at 9:33 AM, Dov Levenglick <dov.levenglick at gmail.com
>> > wrote:
>>
>>> Why isn't $a incrementing in this one-liner:
>>> perl -ibak -pe "$a=1; $a++ if (s/   ADDR_RESET_PAIR/    $a
>>> ADDR_RESET_PAIR/);" file.txt
>>>
>>
>> -p is line based. Perhaps $a is getting initialized every time.
>> If it doesn't maintain the scope, there is no way it will work.
>>
>>
>> _______________________________________________
>> Perl mailing list
>> Perl at perl.org.il
>> http://mail.perl.org.il/mailman/listinfo/perl
>>
>
>
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://mail.perl.org.il/mailman/listinfo/perl
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.perl.org.il/pipermail/perl/attachments/20120220/83a039e2/attachment-0001.htm 


More information about the Perl mailing list