in reply to add double quotes to a perl variable

Note that escaping only '$' may lead to problems in a general case. For example, a string such as 'abc\$xyz' converts to 'abc\\$xyz', where the '$' remains unprotected.

I would suggest using quotemeta(), as your strings are just labels anyway:

#! /usr/bin/perl -l while (<>) { chomp; print '"'.quotemeta.'"' if /^[\$\w]+$/; }

Or simply:
#! /usr/bin/perl -ln print '"'.quotemeta.'"' if /^[\$\w]+$/;

Replies are listed 'Best First'.
Re^2: add double quotes to a perl variable
by tobyink (Canon) on Nov 16, 2013 at 18:57 UTC

    Consider also B::perlstring(), which not only handles escaping, but also adds the quote characters...

    #!/usr/bin/perl -l use B; while (<>) { chomp; print B::perlstring($_) if /^[\$\w]+$/; }

    The B module is bundled with Perl itself, so you already have it. The perlstring() function was added in Perl 5.8, so this will not work on Perl 5.6.

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name