Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Expand variables in single-quoted strings / user input

Regular Expressions

Expand variables in single-quoted strings / user input

by  KevinADC  Posted    (Edited  )
----------------------------
[small]ignore this section:
code
perl
print[/small]
----------------------------


Perl will only expand variables in double-quoted strings. Using a bit a 'magic' you can get perl to expand variables in single-quoted strings as well. This can come in handy for expanding variables in a text file, or user input, or other data:

Code:
[b][color black]my[/color][/b] [color blue]$lamb[/color] [color black]=[/color] [color purple]'[/color][color purple]wolf[/color][color purple]'[/color][color black];[/color]
[b][color black]my[/color][/b] [color blue]$text[/color] [color black]=[/color] [color purple]'[/color][color purple]Mary had a little $lamb.[/color][color purple]'[/color][color black];[/color]
[color blue]$text[/color] [color black]=~[/color] [color purple]s/[/color][color purple]([color black]\$[/color]\w+)[/color][color purple]/[/color][color purple][color blue]$1[/color][/color][color purple]/[/color][color purple]eeg[/color][color black];[/color]
[b][color black]print[/color][/b] [color blue]$text[/color][color black];[/color]

This is genuine variable interpolation, not substitution of one pattern for another. Using the 'e' modifier (you have to use two like in the example for lexical variables) perl will evaluate the replacement pattern as code.

If you are not using "strict" (shame on you) you can use symbolic dereferencing:

Code:
[b][color black]my[/color][/b] [color blue]$lamb[/color] [color black]=[/color] [color purple]'[/color][color purple]wolf[/color][color purple]'[/color][color black];[/color]
[b][color black]my[/color][/b] [color blue]$text[/color] [color black]=[/color] [color purple]'[/color][color purple]Mary had a little $lamb.[/color][color purple]'[/color][color black];[/color]
[color blue]$text[/color] [color black]=~[/color] [color purple]s/[/color][color purple][color black]\$[/color]([color black]\w[/color]+)[/color][color purple]/[/color][color purple][color blue]$[/color]{[color blue]$1[/color]}[/color][color purple]/[/color][color purple]g[/color][color black];[/color]
[b][color black]print[/color][/b] [color blue]$text[/color][color black];[/color]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top