Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^3: Search and replace in all odd lines

by johngg (Canon)
on Jun 25, 2007 at 13:36 UTC ( [id://623170]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Search and replace in all odd lines
in thread Search and replace in all odd lines

perl -i.bak -nle 's/search/replace/g unless $. & 2; print' file

Your one-liner is not going to do what you think. $. & 2 is going to evaluate to true whenever the third second bit from the right (2 is binary 100) is set. Given this input file (lines.txt)

line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9

adapting your one-liner to just print the lines gives

$ perl -nle 'print unless $. & 2;' lines.txt line 1 line 4 line 5 line 8 line 9

Did you actually test your adaptation of GrandFather's idea before posting? Changing between odd and even is as simple as if $. & 1 and unless $. & 1. Perhaps you could have a look at "Bitwise And" in perlop to further your understanding.

Cheers,

JohnGG

Update: Corrected typo.

Update 2: Corrected huge balls-up, thanks fenLisesi. Where did I get "2 is binary 100" from?

Update 3: And thanks clinton, saw your reply after /msg from fenLisesi

Replies are listed 'Best First'.
Re^4: Search and replace in all odd lines
by clinton (Priest) on Jun 25, 2007 at 14:54 UTC
    you missed another typo - 2 is binary 10, not 100

    To flesh out the reasoning:

    DECIMAL BINARY TRUE / FALSE ============= ================= ============ 0 & 2 == 0 000 & 010 == 000 FALSE 1 & 2 == 0 001 & 010 == 000 FALSE 2 & 2 == 2 010 & 010 == 010 TRUE 3 & 2 == 2 011 & 010 == 010 TRUE 4 & 2 == 0 100 & 010 == 000 FALSE 5 & 2 == 0 101 & 010 == 000 FALSE 6 & 2 == 2 110 & 010 == 010 TRUE 7 & 2 == 2 111 & 010 == 010 TRUE

    Clint

      Yes, I've gone bright red :(

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://623170]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (2)
As of 2024-04-20 05:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found