harry34 has asked for the wisdom of the Perl Monks concerning the following question:

i am very very new to perl and need some help !. I have the following lines in a file:
SYMM 1/8 - X, 1/8 + Y, 1/8 + Z SYMM 1/6 - X, 1/6 + Y, 1/6 + Z SYMM 1/4 - X, 1/4 + Y, 1/4 + Z SYMM 1/2 - X, 1/2 + Y, 1/2 + Z
..and I am using the following script below to initially undef SYMM and store the lines in the 4 variables $symmetry. Then by numerous splits (excuse the temporary and crude names of the variables!) I isolate the individual fractions and calculate their values (i.e 1/8)=($frac1[0]/$frac2[0])=(0.125). Question: How would I modify the script below to give me a loop which prints out of all the fraction values. At the moment I can only get print out of 0.5 0.5 0.5 for the last line as the others are overwritten. Hope this is clear ! Any takers ! cheers
if (/SYMM/) { (undef, $symmetry[$i]) = split /SYMM\s+/; ($symm[$i], $symm[$i], $symm[$i]) = split /,\s+/, $symmetry[$i]; $i++; next LOOP; } } close (IN); foreach $i(0..$symm) { if ($symm[$i] !~ /\d{1}/) { ($tmp2[$i], $tmp3[$i]) = split /\s+/, @symm[$i]; $tmp1[$i] = 0; }else{ ($tmp1[$i], $tmp2[$i], $tmp3[$i]) = split /\s+/, @symm[$i]; } ($frac1[$i], $frac2[$i]) = split (/\//, @tmp1[$i]); } print @value[0] = ($frac1[0]/$frac2[0]); print "\n"; print @value[2] = ($frac1[1]/$frac2[1]); print "\n"; print @value[3] = ($frac1[2]/$frac2[2]);

Edit Masem 2001-12-15 - Added CODE tags in text description

Replies are listed 'Best First'.
Re: Help with loops
by Trimbach (Curate) on Dec 15, 2001 at 19:04 UTC
    If I understand what you want, you just want to evaluate the fractions in each line as decimals, ignoring the "-x", "+Y" etc. Well, this does what you want:
    while (<DATA>) { @fractions = m!(\d+/\d+)!g; print eval($_), " " foreach @fractions; print "\n"; } __DATA__ SYMM 1/8 - X, 1/8 + Y, 1/8 + Z SYMM 1/6 - X, 1/6 + Y, 1/6 + Z SYMM 1/4 - X, 1/4 + Y, 1/4 + Z SYMM 1/2 - X, 1/2 + Y, 1/2 + Z
    This code takes advantage of the fact that the "match" operator (m//) provides an array of every match when used with the /g modifier. Doing it this way lets us dispense with all those messy splits. The "eval" command tells Perl to actually "do the math" with the resulting fractions, printing (for example) "0.5" rather than just the string "1/2".

    Your next question might be on how round the resulting fractions accordingly. For that, I point you to perfunc and the sprintf function.

    Enjoy!

    Gary Blackburn
    Trained Killer

Re: Help with loops
by hopes (Friar) on Dec 15, 2001 at 22:07 UTC
    If you want to obtain the entire expression, not only the fraction, you can try this:
    while (<DATA>) { s!\d+/\d+!$&!gee; print; } __DATA__ SYMM 1/8 - X, 1/8 + Y, 1/8 + Z SYMM 1/6 - X, 1/6 + Y, 1/6 + Z SYMM 1/4 - X, 1/4 + Y, 1/4 + Z
    which basically matches all the fractions and substitute them by themselves evaluated (The numeric value)

    Hopes
    $_=$,=q,\,@4O,,s,^$,$\,,s,s,^,b9,s, $_^=q,$\^-]!,,print