[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: interpreting a strongly typed regexp constant variable as literal re
From: |
Manuel Collado |
Subject: |
Re: interpreting a strongly typed regexp constant variable as literal regular expression? |
Date: |
Sat, 30 May 2020 22:46:31 +0200 |
User-agent: |
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.5.0 |
El 30/05/2020 a las 18:28, Craig escribió:
Ok,
This was originally asked in comp.lang.awk
And subsequently answered in comp.lang.awk.
For the given examples, Script 1 generates the desired output.
The desired output for script 2 should be the same the output
generated by script 1.
As provided, in script 2, the 'Yes" is printed as the 4th record
instead of 2nd record because @/var/ isn't interpreted as an
actual regular expression, but as a string (as in script 3's
example).
typeof() shows the script 2 variable as being type regexp.
Thanks,
Craig
===== script 1
awk '{
switch($0) {
case /^a/ :
print "Yes"
break
default :
print "NR: " NR
break
}
}' << END
g
a
c
@/a/
END
==== script 1 output:
NR: 1
Yes
NR: 3
NR: 4
===== script 2
awk '{ var = @/^a/
switch($0) {
case @/var/ :
print "Yes"
break
default :
print "NR: " NR
break
}
}' << END
g
a
c
@/var/
END
==== script 2 output
NR: 1
NR: 2
NR: 3
Yes
El 30/05/2020 a las 21:50, Craig escribió: (private mail)
> I'd be nice to just be able to just add @ before the switch keyword,
> ( aka @switch) to indicate to awk that at runtime the strongly typed
> regular expression(s) in switch block should be updated with constants
> before awk executes the @switch block.
The switch statement requires constant values as case labels. If you
want them to be evaluated dynamically, just replace the switch with a
cascade of if/else
{ var = @/^a/
if ($0 ~ var) {
print "Yes"
} else {
print "NR: " NR
}
}
--
Manuel Collado - http://mcollado.z15.es