SPUG: range operator
Florentin
florentin_ at hotmail.com
Thu Mar 29 20:00:37 PDT 2007
Thank you everybody for explanations and interpreting perldoc pages.
Florentin.
Jacinta Richardson wrote:
> Florentin wrote:
>> # Expect to print only a and b --> it prints all from x1 to x3 as above
>> while( <>) {
>> if(/$start/+1 ../$end/-1) {
>> print ;
>> }
>> }
>
> After running through Perltidy, this is the same as writing:
>
> while (<>) {
> if ( /$start/ + 1 .. /$end/ - 1 ) {
> print;
> }
> }
>
> which of course is the same as writing:
>
> while (<>) {
> if ( ((/$start/) + 1) .. ((/$end/) - 1) ) {
> print;
> }
> }
>
> So, we're doing the regular expression (in a scalar context) and it's
> returning true or false then we're adding (or subtracting) one from
> that value. So to walk through you're input we get:
>
> # cat _a # first regexp returns false, add 1 to make true
> # x1 # end of range is false
> # a # end of range still false
> # x5 # second regexp returns true, minus 1 for a value
> of false
> # x1 # end of range still false
> # b # end of range still false
> # x3 # second regexp: true minus 1, end of range still
> false
> # c # end of range still false
> # d # end of range still false
>
> so it prints everything. Thanks to the plus one, the first part of
> your range is always true, and the minus one causes the end of the
> range to be false even when the regexp is true.
>
> I'm not quite sure what you wished to achieve with the above code, but
> that probably wasn't it.
>
>> # Expect to print only a and b --> prints nothing ??
>> while( my $x = <>) {
>> if($x=~m/$start/+1 .. $x=~m/$end/-1){
>> print ;
>> }
>> }
>
> This behaves the same as the previous one. Except you're printing $_
> rather than $x. If you had turned warnings on for your test code,
> Perl would have told you about this.
>
> All the best,
>
> Jacinta
>
>
More information about the spug-list
mailing list