How can I make this Perl one-liner to toggle character in line in a file?

I am attempting to write a one-line Perl script that will toggle a line in a configuration file from "commented" to not and back. I have the following so far:

perl -pi -e 's/^(#?)(\tDefaultServerLayout)/ ... /e' xorg.conf

I am trying to figure out what code to put in the replacement (...) section. I would like the replacement to insert a '#' if one was not matched on, and remove it if it was matched on.

pseudo code:

if ( $1 == '#' ) then
   print $2
   print "#$2"

My Perl is very rusty, and I don't know how to fit that into a s///e replacement.

My reason for this is to create a single script that will change (toggle) my display settings between two layouts. I would prefer to have this done in only one script.

I am open to suggestions for alternate methods, but I would like to keep this a one-liner that I can just include in a shell script that is doing other things I want to happen when I change layouts.


perl -pi -e 's/^(#?)(?=\tDefaultServerLayout)/ ! $1 && "#" /e' foo

Note the addition of ?= to simplify the replacement string by using a look-ahead assertion.

Some might prefer s/.../ $1 ? "" : "#" /e.

Need Your Help

How to understand "rake db:seed"

ruby-on-rails database seed dbmigrate

I am using Michael Hartl's rails tutorials.

WoopraTracker is not defined in custom event data

javascript analytics

i'm trying to implement Woopra custom event data on page load, and i'm using their guidelines