3
\$\begingroup\$

I had to come up with a way to convert sqrt(#) into its actual numeric value because before I would have an array containing elements such as:

[sqrt(3), -sqrt(3), 1]

If I tried to multiply, I would get the error:

Argument "-sqrt(3)" isn't numeric in multiplication (*)

Here is my work-around, but I think there's a better way. Any suggestions?

#!/usr/bin/perl
#perl Solver.pl

use strict;
use warnings;


my $roots = "Sqrt[3] ||-Sqrt[3] ||1";
my @rootList = split(/ \|\|/, $roots); # fill array with string's values separated by " ||"


# Convert any Sqrt numbers to numerical value 
# (ex.) Sqrt[3] -> sqrt(3)
for $_ ( @rootList ){
    $_ =~ s/Sqrt\[/sqrt(/g; # Sqrt[ -> sqrt(
    $_ =~ s/\]/)/g; # ] -> )

    if( $_ =~ /-sqrt/ ){ # replace string of negative sqrt()
        my $temp = substr( $_, 6 ); # take "#)"
        $temp =~ s/\)//g; # remove ")"
        $_ = -1*sqrt( $temp );
    }
    elsif( $_ =~ /sqrt/ ){ # replace positive sqrt()
        my $temp = substr( $_, 5 );
        $temp =~ s/\)//g;
        $_ = sqrt( $temp );
    }
}

print "[@rootList]\n";
\$\endgroup\$
3
\$\begingroup\$

I found the use of Sqrt[...] to be cumbersome, why have the case in that format, and why have the [] style braces?

I would normally not recommend this, but a simple solution, if you trust, or can sanitize your inputs, is to just use the eval function.

for $_ ( @rootList ){
    $_ =~ s/Sqrt\[(.+)\]/sqrt($1)/;
    $_ = eval($_);
    $@ and die $@;
}

That does it..... all of it. Convert Sqrt[...] to sqrt(...), and eval the result.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ I receive the list of values from Mathematica output in bracket format and do some string manipulation to make it look nicer. Thanks! Nice solution. \$\endgroup\$ – Kolibrie Jun 10 '15 at 4:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.