Executing code on a match

Inside a parse rule, we can provide code that will only be executed when a match is found. This code must be enclosed within parentheses ( ).

For example, here we simply print out the data variable, after the to rule has found a match:

parse rate [thru "<title>" copy data to "</title>" (print data) to end]
;1 USD = 0.81191502 EUR ;== true

Now let's turn to the complete rates file again—rates: read %rates.xml.

To parse through the complete file extracting information from each <title> tag, we can use any from the previous section as follows:

any [thru "<title>" copy data to "</title>"]

Each time it finds a <title> tag, the condition becomes true and the data is copied. Verify for yourself that all will not work here; why would that be?

To store each data item, we need to use code to append this item to a previously declared series, usd

usd: copy []
parse rates [ any [thru "<title>" copy data to "</title>" (append usd data)] ]
usd ;== [{XML Daily Foreign Exchange Rates for U.S. Dollar (USD)} "1 USD = 0.81191502 EUR" "1 USD = 0.70675954 GBP" "1 USD = 0.94840517 CHF" "1 USD = 1.29753098 CAD" "1 USD = 1.294292...

We see that usd now contains strings with the exchange rates. The first string is the title of the XML file itself, which we can eliminate by positioning it right before the first usable data item:

parse rates [
thru </lastBuildDate>
any [thru "<title>" copy data to "</title>" (append usd data)]
]

Now usd is as follows:

["1 USD = 0.81191502 EUR" "1 USD = 0.70675954 GBP" "1 USD = 0.94840517 CHF" "1 USD = 1.29753098 CAD" "1 USD = 1.29429260 AUD" "1 USD = 105.59598315 JPY" "1 USD = 114.07517952 ...

This is not the most efficient form to contain this data. Perhaps we would like our data in this form:

[ "EUR" 0.81191502 "GPB" 0.70675954 ... ]

We can see that this information is contained in the <targetCurrency> and <exchangeRate> tags. With the tools you have acquired now, this is easy to do.

=> Answer question 8 from the Questions section then also answer question 9.

Having extracted the data in a series, we can now use all other Red tools at our disposal to work with that data.

The variables can be used in more flexible ways together; they are known in other pieces of parse code, as this example shows:

parse "xxxyyy" [copy letters some "x" (n: length? letters) n "y"] ;== true
letters ;== "xxx"

The match of some "x" is copied out into letters. The length of the letters word sets the number of following y characters that are going to be matched.

copy can also be used on other types. Here is an example of copy used on a binary value:

parse #{FFFFDECAFBAD000000} [
2 #{FF}
copy data to #{00}
some #{00}
] ;== true
data ;== #{DECAFBAD}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.5.12