Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string to literal conversion

Status
Not open for further replies.

codemut

Programmer
Feb 29, 2008
26
US
Based on this code...

BEGIN {
str = "2+2"
split(str,arr,"")
print arr[1] arr[2] arr[3]
}

...how can one simply convert the string arr[2] to the + math operator so as to print 4?
 
Unless you want to implement a complete mathematical expression interpreter (which could be easy or difficult, depending on how complex you want the expression support to be) you could simply pass the expression to an external utility which is designed to do that job already, e.g. bc.

Code:
awk '
        BEGIN {
                str="2+2"
                "echo " str " | bc " | getline result
                print result
        }
'

Annihilannic.
 
Hi

Or we can stay with [tt]awk[/tt] : ;-)
Code:
awk '
        BEGIN {
                str="2+2"
                "[highlight]awk \"BEGIN{print[/highlight] " str "[highlight]}\"[/highlight]" | getline result
                print result
        }
'

Feherke.
 
Thanks so far ... but plucking out the '+' is key. If only there was something like strtonum(arr[2]) to force '+' to function.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top