I'm writing a simple Perl script that translates assembly instruction strings to 32-bit binary code.
I decided to handle translation grouping instruction by type (ADD
and SUB
are R-Type instructions and so on...) so in my code I'm doing something like this:
my $bin = &r_type($instruction) if $instruction =~ /^(?:add|s(?:ub|lt|gt))\s/;
because I want to handle add
, sub
, slt
and sgt
in the same way.
I realized however that maybe using that regular expression could be an 'overkill' for the task I'm supposed to do... could the pattern
/^(?:add|sub|slt|sgt)\s/
represent a better use of regular expressions in this case?
Thanks a lot.
* - means "0 or more instances of the preceding regex token"
If a and b are regular expression, a + b is also a regular expression with language {a,b}. If a and b are regular expression, ab (concatenation of a and b) is also regular. If a is regular expression, a* (0 or more times a) is also regular.
Regular expressions are useful in search and replace operations. The typical use case is to look for a sub-string that matches a pattern and replace it with something else. Most APIs using regular expressions allow you to reference capture groups from the search pattern in the replacement string.
Example : The regular expression ab+c will give abc, abbc, abbc, … and so on. The curly braces {…}: It tells the computer to repeat the preceding character (or set of characters) for as many times as the value inside this bracket.
Unless you are using a perl older than 5.10, the simple alternation will perform better anyway (see here), so there is no reason to try to optimize it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With