compare two variables via regex

66 views
Skip to first unread message

Lori Cho

unread,
Dec 5, 2014, 6:16:02 PM12/5/14
to puppet...@googlegroups.com
I have two variables and I want to compare them to each other.  However, the regex doesn't return true, because it seems to treat the variable in the // as a literal.  

Something like this:

$variable1 = 'foo'
$variable2 = 'foobar'

if($variable2 =~ /$variable1/) {
        notify {"it works":}
} else {
        notify {"regex did not work":}
}

root@test-slincsplunk1101r(~)# puppet apply /srv/tmp/test.pp
notice: regex did not work
notice: /Stage[main]//Notify[regex did not work]/message: defined 'message' as 'regex did not work'


How can I do this?


Ramin K

unread,
Dec 5, 2014, 7:43:14 PM12/5/14
to puppet...@googlegroups.com
The docs say it's not available.
https://docs.puppetlabs.com/puppet/latest/reference/lang_datatypes.html#regular-expressions

"Alternate forms of regex quoting are not allowed and Ruby-style
variable interpolation is not available."

Ramin


Felix Frank

unread,
Dec 10, 2014, 7:46:34 AM12/10/14
to puppet...@googlegroups.com
As a workaround, you can resort to a custom function, or even
inline_template.

Please note that this is horrible and should likely not be used in real
life. Consider it a last ditch.

if inline_template('<%= @variable2 =~ /#{@variable1}/ %>') == 'true' { }

Be aware that inline_template carries a compiler performance penalty.
And don't use this particular example at all ;-)

Felix

Henrik Lindberg

unread,
Dec 13, 2014, 6:24:02 PM12/13/14
to puppet...@googlegroups.com
In Puppet 3.7 with future parser the right hand side can be any
expression that evaluates to a regular expression or a string (if string
it is
interpreted as a regexp and the string should not be enclosed in / /).
This will be standard in Puppet 4.0.

e.g

# The variable is a regexp string
if($variable2 =~ $variable) {
#...

# interpolated as part of a regext
if($variable2 =~ "xxxxx$variable") {
#...

Hope that helps
Regards
- henrik

--

Visit my Blog "Puppet on the Edge"
http://puppet-on-the-edge.blogspot.se/


Reply all
Reply to author
Forward
0 new messages