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
else
   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.

Answers


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

WCF not allowing large list . Throwing “The remote server returned an unexpected response: (400) Bad Request.” exception

c# asp.net wcf silverlight

I have a list which has 9 fields. When i pass A smaller list (say 50 rows) the application is working fine. If i pass a larger list my service is throwing the exception "The remote server returned an

MySQL INSERT else if exists UPDATE

php mysql insert

I'm building a config table with two columns, config_name and config_value. I insert multiple rows in one statement:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.