regex question

N

new2perl

Trying to match a variable such as: $name

or

a hashvar such as: $name{var1}


Tried s/\$(\w+)/g but that only matches $name.

Also tried s/\$(\w+{?\w*}? - not working.

Bob.
 
G

Gunnar Hjalmarsson

Trying to match a variable such as: $name

or

a hashvar such as: $name{var1}


Tried s/\$(\w+)/g but that only matches $name.

Also tried s/\$(\w+{?\w*}? - not working.

What are you trying to achieve? Are you trying to resolve variables in a
template? Perl variables are not well suited as template variables.

Anyway, to just answer your question, this would match both your examples:

\$\S+

You probably want to read this FAQ entry:

perldoc -q "expand variables"
 
J

John W. Krahn

Gunnar said:
What are you trying to achieve? Are you trying to resolve variables in a
template? Perl variables are not well suited as template variables.

Anyway, to just answer your question, this would match both your examples:

\$\S+

Except where it won't:

$ perl -le'%x = "A" .. "F"; print $x { C }'
D


perl usually ignores whitespace.



John
 
T

Tad McClellan

Trying to match a variable such as: $name


Why are you trying to match a variable such as: $name ?

What about

${name}
$main::name

??

or

a hashvar such as: $name{var1}
^^^^

A hash key can be any Perl expression.

You need to parse nearly the entire Perl language to do that reliably.

A Perl expression can be nested to an arbitrary depth, so it is
mathematically impossible to parse them with a regular expression.

That road leads to madness.

Give up.

Tried s/\$(\w+)/g but that only matches $name.

Also tried s/\$(\w+{?\w*}? - not working.


This is almost certainly an XY problem.

You should use a templating system if that is what your Y is.
 
G

Gunnar Hjalmarsson

John said:
Except where it won't:

$ perl -le'%x = "A" .. "F"; print $x { C }'
D

perl usually ignores whitespace.

I don't understand your objection. The OP's examples are:

$name
$name{var1}

If you use Perl variables as template variables, which I don't think you
should, you can obviously apply a more restrictive format than what the
Perl interpreter would understand.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,204
Messages
2,571,063
Members
47,670
Latest member
micheljon

Latest Threads

Top