What does the symbol "~" mean in VCL? - varnish

I am seeing that this is used in varnish vcl if statements "~"
if (req.url ~ "phpMyAdmin") {
return (pass);
}
I understand that it works like == some time like in_array()
if ( req.http.User-Agent ~ "(Android|iPhone|iPad|BlackBerry|SAMSUNG)")
return(pass);
}
Can someone please explain what does it actually mean.
Is it also a default php operator? and what's the difference between it and using ==

According to the official documentation, ~ is the match operator.
== compares two values, returns true if they are equal
~ checks the value against the regular expression, returns true if the value is a match
~ Match. Can either be used with regular expressions or ACLs.
# match an IP address against an ACL
if (client.ip ~ local) {
return (pipe);
}
Varnish uses Perl-compatible regular expressions (PCRE). To send flags to the PCRE engine, such as to do case insensitive matching, add the flag within parens following a question mark, like this:
# If host is NOT example dot com..
if (req.http.host !~ "(?i)example\.com$") {
...
}

I think there is no any symbol like "~" in php.
Already checked with php documentation.

Related

puppet manifest check if variable is not empty

Following this existing link - Puppet how to tell if a variable is set. which is , below is the piece of the puppet manifest script :
if defined('$to_dir') {
notify { "Fourthvalue of $from_dir and $to_dir ... ":}
notify { "Fourth$to_dc... ":}
$worker_name = "acme${port}_${machine}${from_dir}_${to_dir}"
$system_id = "${machine}${from_dir}.${to_dir}
} else {
$worker_name = "acme${port}_${machine}_${pod}"
$system_id = $::fqdn
}
However, when we pass "to_dir" as null, it is still going into if block as actual(expect to be in else block).
Even tried using if $to_dir { or if $to_dir != undef { , this did not help.
The value of "to_dir" will be a word either "abc" or "def".
Please advise if something is wrong..
puppet manifest check if variable is not empty
You're throwing around a variety of terms -- "defined", "empty", "null" -- that mean different things or nothing in Puppet. But taken in toto, I think your purpose would be served by testing whether the variable in question is defined and contains a nonempty string. You can do that by matching the variable against an appropriate type expression. For example,
if $to_dir =~ String[1] {
# ...
}
That tests that variable $to_dir contains a string at least one character long. The condition will evaluate to false if $to_dir has not been assigned a value, or if it has been assigned a value of a type different from String, or if its value is an empty string. If the value is a string, it puts no other requirements on the contents. In particular, the value could consist only of one or more space characters.
i think the main issue here is that a variable which is instantiated with $var = undef is a defined variable with a value set to undef (its imo not well named). that said you checking the truthy state or undef (or using something specific to the datatype like size or empty) should all work. e.g.
# at this point defined('$var') == false
$var = undef
# now defined('$var') evalutes to false
# you should be able to check with the following that evaluate to true
($var == undef)
!$var
# you can also use the following which evaluates to false
$var =~ NotUndef

Understanding Raku's `&?BLOCK` compile-time variable

I really appreciate the Raku's &?BLOCK variable – it lets you recurse within an unnamed block, which can be extremely powerful. For example, here's a simple, inline, and anonymous factorial function:
{ when $_ ≤ 1 { 1 };
$_ × &?BLOCK($_ - 1) }(5) # OUTPUT: «120»
However, I have some questions about it when used in more complex situations. Consider this code:
{ say "Part 1:";
my $a = 1;
print ' var one: '; dd $a;
print ' block one: '; dd &?BLOCK ;
{
my $a = 2;
print ' var two: '; dd $a;
print ' outer var: '; dd $OUTER::a;
print ' block two: '; dd &?BLOCK;
print "outer block: "; dd &?OUTER::BLOCK
}
say "\nPart 2:";
print ' block one: '; dd &?BLOCK;
print 'postfix for: '; dd &?BLOCK for (1);
print ' prefix for: '; for (1) { dd &?BLOCK }
};
which yields this output (I've shortened the block IDs):
Part 1:
var one: Int $a = 1
block one: -> ;; $_? is raw = OUTER::<$_> { #`(Block|…6696) ... }
var two: Int $a = 2
outer var: Int $a = 1
block two: -> ;; $_? is raw = OUTER::<$_> { #`(Block|…8496) ... }
outer block: -> ;; $_? is raw = OUTER::<$_> { #`(Block|…8496) ... }
Part 2:
block one: -> ;; $_? is raw = OUTER::<$_> { #`(Block|…6696) ... }
postfix for: -> ;; $_ is raw { #`(Block|…9000) ... }
prefix for: -> ;; $_ is raw { #`(Block|…9360) ... }
Here's what I don't understand about that: why does the &?OUTER::BLOCK refer (based on its ID) to block two rather than block one? Using OUTER with $a correctly causes it to refer to the outer scope, but the same thing doesn't work with &?BLOCK. Is it just not possible to use OUTER with &?BLOCK? If not, is there a way to access the outer block from the inner block? (I know that I can assign &?BLOCK to a named variable in the outer block and then access that variable in the inner block. I view that as a workaround but not a full solution because it sacrifices the ability to refer to unnamed blocks, which is where much of &?BLOCK's power comes from.)
Second, I am very confused by Part 2. I understand why the &?BLOCK that follows the prefix for refers to an inner block. But why does the &?BLOCK that precedes the postfix for also refer to its own block? Is a block implicitly created around the body of the for statement? My understanding is that the postfix forms were useful in large part because they do not require blocks. Is that incorrect?
Finally, why do some of the blocks have OUTER::<$_> in the but others do not? I'm especially confused by Block 2, which is not the outermost block.
Thanks in advance for any help you can offer! (And if any of the code behavior shown above indicates a Rakudo bug, I am happy to write it up as an issue.)
That's some pretty confusing stuff you've encountered. That said, it does all make some kind of sense...
Why does the &?OUTER::BLOCK refer (based on its ID) to block two rather than block one?
Per the doc, &?BLOCK is a "special compile variable", as is the case for all variables that have a ? as their twigil.
As such it's not a symbol that can be looked up at run-time, which is what syntax like $FOO::bar is supposed to be about afaik.
So I think the compiler ought by rights reject use of a "compile variable" with the package lookup syntax. (Though I'm not sure. Does it make sense to do "run-time" lookups in the COMPILING package?)
There may already be a bug filed (in either of the GH repos rakudo/rakudo/issues or raku/old-issues-tracker/issues) about it being erroneous to try to do a run-time lookup of a special compile variable (the ones with a ? twigil). If not, it makes sense to me to file one.
Using OUTER with $a correctly causes it to refer to the outer scope
The symbol associated with the $a variable in the outer block is stored in the stash associated with the outer block. This is what's referenced by OUTER.
Is it just not possible to use OUTER with &?BLOCK?
I reckon not for the reasons given above. Let's see if anyone corrects me.
If not, is there a way to access the outer block from the inner block?
You could pass it as an argument. In other words, close the inner block with }(&?BLOCK); instead of just }. Then you'd have it available as $_ in the inner block.
Why does the &?BLOCK that precedes the postfix for also refer to its own block?
It is surprising until you know why, but...
Is a block implicitly created around the body of the for statement?
Seems so, so the body can take an argument passed by each iteration of the for.
My understanding is that the postfix forms were useful in large part because they do not require blocks.
I've always thought of their benefit as being that they A) avoid a separate lexical scope and B) avoid having to type in the braces.
Is that incorrect?
It seems so. for has to be able to supply a distinct $_ to its statement(s) (you can put a series of statements in parens), so if you don't explicitly write braces, it still has to create a distinct lexical frame, and presumably it was considered better that the &?BLOCK variable tracked that distinct frame with its own $_, and "pretended" that was a "block", and displayed its gist with a {...}, despite there being no explicit {...}.
Why do some of the blocks have OUTER::<$_> in them but others do not?
While for (and given etc) always passes an "it" aka $_ argument to its blocks/statements, other blocks do not have an argument automatically passed to them, but they will accept one if it's manually passed by the writer of code manually passing one.
To support this wonderful idiom in which one can either pass or not pass an argument, blocks other than ones that are automatically fed an $_ are given this default of binding $_ to the outer block's $_.
I'm especially confused by Block 2, which is not the outermost block.
I'm confused by you being especially confused by that. :) If the foregoing hasn't sufficiently cleared this last aspect up for you, please comment on what it is about this last bit that's especially confusing.
During compilation the compiler has to keep track of various things. One of which is the current block that it is compiling.
The block object gets stored in the compiled code wherever it sees the special variable $?BLOCK.
Basically the compile-time variables aren't really variables, but more of a macro.
So whenever it sees $?BLOCK the compiler replaces it with whatever the current block the compiler is currently compiling.
It just happens that $?OUTER::BLOCK is somehow close enough to $?BLOCK that it replaces that too.
I can show you that there really isn't a variable by that name by trying to look it up by name.
{ say ::('&?BLOCK') } # ERROR: No such symbol '&?BLOCK'
Also every pair of {} (that isn't a hash ref or hash index) denotes a new block.
So each of these lines will say something different:
{
say $?BLOCK.WHICH;
say "{ $?BLOCK.WHICH }";
if True { say $?BLOCK.WHICH }
}
That means if you declare a variable inside one of those constructs it is contained to that construct.
"{ my $a = "abc"; say $a }"; # abc
say $a; # COMPILE ERROR: Variable '$a' is not declared
if True { my $b = "def"; say $b } # def
say $b; # COMPILE ERROR: Variable '$b' is not declared
In the case of postfix for, the left side needs to be a lambda/closure so that for can set $_ to the current value.
It was probably just easier to fake it up to be a Block than to create a new Code type just for that use.
Especially since an entire Raku source file is also considered a Block.
A bare Block can have an optional argument.
my &foo;
given 5 {
&foo = { say $_ }
}
foo( ); # 5
foo(42); # 42
If you give it an argument it sets $_ to that value.
If you don't, $_ will point to whatever $_ was outside of that declaration. (Closure)
For many of the uses of that construct, doing that can be very handy.
sub call-it-a (&c){
c()
}
sub call-it-b (&c, $arg){
c( $arg * 10 )
}
for ^5 {
call-it-a( { say $_ } ); # 0␤ 1␤ 2␤ 3␤ 4␤
call-it-b( { say $_ }, $_ ); # 0␤10␤20␤30␤40␤
}
For call-it-a we needed it to be a closure over $_ to work.
For call-it-b we needed it to be an argument instead.
By having :( ;; $_? is raw = OUTER::<$_> ) as the signature it caters to both use-cases.
This makes it easy to create simple lambdas that just do what you want them to do.

What is the difference between ==~ and != in Groovy?

What is the difference between these?
Why use one over the other?
def variable = 5
if( variable ==~ 6 && variable != 6 ) {
return '==~ and != are not the same.'
} else {
return '==~ and != are the same.'
}
In groovy, the ==~ operator (aka the "match" operator) is used for regular expression matching. != is just a plain old regular "not equals". So these are very different.
cf. http://groovy-lang.org/operators.html
In Java, != is “not equal to” and ~ is "bitwise NOT". You would actually be doing variable == ~6.
In Groovy, the ==~ operator is "Regex match". Examples would be:
"1234" ==~ /\d+/ -> evaluates to true
"nonumbers" ==~ /\d+/ -> evaluates to false
In Groovy you also have to be aware that in addition to ==~, alias "Match operator", there is also =~, alias "Find Operator" and ~, alias "Pattern operator".
All are explained here.
==~ result type: Boolean/boolean (there are no primitives in Groovy, all is not what it seems!)
=~ result type: java.util.regex.Matcher
~ result type: java.util.regex.Pattern
I presume the Groovy interpreter/compiler can distinguish between ~ used as a Pattern operator and ~ used as a bitwise NOT (i.e. its use in Java) through context: the former will always be followed by a pattern, which will always be bracketed in delimiters, usually /.

Token empty when matching grammar although rule matched

So my rule is
/* Addition and subtraction have the lowest precedence. */
additionExp returns [double value]
: m1=multiplyExp {$value = $m1.value;}
( op=AddOp m2=multiplyExp )* {
if($op != null){ // test if matched
if($op.text == "+" ){
$value += $m2.value;
}else{
$value -= $m2.value;
}
}
}
;
AddOp : '+' | '-' ;
My test ist 3 + 4 but op.text always returns NULL and never a char.
Does anyone know how I can test for the value of AddOp?
In the example from ANTLR4 Actions and Attributes it should work:
stat: ID '=' INT ';'
{
if ( !$block::symbols.contains($ID.text) ) {
System.err.println("undefined variable: "+$ID.text);
}
}
| block
;
Are you sure $op.text is always null? Your comparison appears to check for $op.text=="+" rather than checking for null.
I always start these answers with a suggestion that you migrate all of your action code to listeners and/or visitors when using ANTLR 4. It will clean up your grammar and greatly simplify long-term maintenance of your code.
This is probably the primary problem here: Comparing String objects in Java should be performed using equals: "+".equals($op.text). Notice that I used this ordering to guarantee that you never get a NullPointerException, even if $op.text is null.
I recommend removing the op= label and referencing $AddOp instead.
When you switch to using listeners and visitors, removing the explicit label will marginally reduce the size of the parse tree.
(Only relevant to advanced users) In some edge cases involving syntax errors, labels may not be assigned while the object still exists in the parse tree. In particular, this can happen when a label is assigned to a rule reference (your op label is assigned to a token reference), and an error appears within the labeled rule. If you reference the context object via the automatically generated methods in the listener/visitor, the instances will be available even when the labels weren't assigned, improving your ability to report details of some errors.

TCL use "eq" or "==" when the argument can be a list or a string

I have the following if loop:
if { expr { $Node_3 eq "BadAngle" } } {
return "BadAngle"
}
Node_3 can be a list containing coordinates, or the simple string "BadAngle"
I use TCLPro 1.4 for debugging and TCL 8.6. I get:
*syntax error in expression " expr { $Node_3 eq "BadAngle" } "*
I then also tried:
if { [ expr { $Node_3 eq "BadAngle" ] == 1 } } {
return "BadAngle"
}
But i get the same error.
Also: What is the better alternative in this case: To use "==" or "eq", I think "eq" because a list is a kind of a string..or?
You seem to be getting in a bit of a pickle there. Firstly, you probably don't want to use expr inside the if condition, so this will be enough:
if { $Node_3 eq "BadAngle" } {
return "BadAngle"
}
Since one of the things you are comparing against is definitely non-numeric, you'll be fine using the eq operator though the == operator is equivalent. The only time there is a difference is when both operands look like numbers, when == will compare them as numbers (parsing them into numbers if necessary). This means that "1" == "0x01" despite them being rather different strings; the eq operator always compares as strings.
How to choose which is best? It's actually pretty easy: do you think you are working with numbers at this point on both sides of the comparison? If yes, use ==, and otherwise use eq.
The one time you want to use expr inside if is when you're dynamically selecting the operator. This is not really recommended, but you'd do it like this:
set op "=="
if { [expr {$Node_3} $op {"BadAngle"} ]} {
return "BadAngle"
}
It's pretty ugly. (Notice that I put everything else inside its own braces to prevent double evaluation, and I'm careful with balancing all the brackets correctly, which is what was tripping you up in the code in your question.) Don't do it unless you really really need to.
You have two distinct problems in your attempts:
In the first example you're trying to call expr in a wrong way: if (and other commands which support conditions, such as while) use the same machinery to evaluate their condition the expr command does — to cite the manual:
The if command evaluates expr1 as an expression (in the same way that expr evaluates its argument).
Now that machinery sees a bare word "expr" and has no idea what to do with it.
There are two ways to fix the code:
Wrong way — properly call expr:
if {[expr {$Node_3 eq "BadAngle"}]} { ... }
This is wrong because the nested call to expr is purely superficial.
Correct way — just drop unneeded expr:
if {$Node_3 eq "BadAngle"} { ... }
In the second example you decided to make the situaton more complicated by introducing another boolean test (not needed as the eq and == operators already return a value of type boolean). But in this case you forgot to put the closing curly brace, }, which performs grouping, for the code should have been
if { [ expr { $Node_3 eq "BadAngle" } ] == 1 } } { ... }
In any case the correct solution is to simply use
if {$Node_3 eq "BadAngle"} { ... }

Resources