Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

What makes good Perl code?

by slinky773 (Sexton)
on Aug 15, 2011 at 19:51 UTC ( #920343=perlquestion: print w/ replies, xml ) Need Help??
slinky773 has asked for the wisdom of the Perl Monks concerning the following question:

Before I took up Perl, I was learning Java. I was looking through the Oracle Java Programming forums, and I saw a link to an article that said the best type of perl code is "dumb code", or code that is very straightforward and almost spells out what you're doing. I was wondering, dumb code is good for Java, but what is the best type of perl code? Consider the following code:
#!/usr/bin/perl -w use strict; use warnings; print "I will calculate whatever\n"; print "you specify according to\n"; print "Ohm's law. What shall I\n"; print "calculate? Type either\n"; print "voltage, current, or\n"; print "resistance.\n"; my $i = 0; while($i == 0) { my $calculation = <STDIN>; chomp $calculation; if($calculation =~ m/voltage/) { print "Type the current of the circuit.\n"; print "Add mA at the end of your answer\n"; print "if your answer is in milliAmps.\n"; my $current = <STDIN>; chomp $current; print "Now type the resistance of the circuit.\n"; my $resistance = <STDIN>; chomp $resistance; if($current =~ m/mA/) { $current =~ s/mA//; $current =~ s/^\s+//; $current =~ s/ //; $current /= 1000; } else { } my $voltage = $current * $resistance; print "Ohm's law is V = IR, so the voltage of\n"; print "the circuit is $voltage volts.\n"; $i++; } elsif($calculation =~ m/current/) { print "Type the resistance of the circuit.\n"; my $resistance = <STDIN>; chomp $resistance; print "Now type the voltage of the circuit.\n"; my $voltage = <STDIN>; chomp $voltage; my $current = $voltage / $resistance; chomp $current; my $otherCurrent = $current / 1000; chomp $otherCurrent; print "Ohm's law is V = IR, so the current of\n"; print "the circuit is $current amps,\n"; print "or $otherCurrent milliAmps.\n"; $i++; } elsif($calculation =~ m/resistance/) { print "Type the current of the circuit.\n"; print "Add mA at the end of your answer\n"; print "if your answer is in milliAmps.\n"; my $current = <STDIN>; chomp $current; print "Now type the voltage of the circuit.\n"; my $voltage = <STDIN>; chomp $voltage; if($current =~ m/mA/) { $current =~ s/mA//; $current =~ s/^\s+//; $current =~ s/ //; $current /= 1000; } else { } my $resistance = $voltage / $current; chomp $resistance; print "Ohm's law is V = IR, so the resistance of\n"; print "the circuit is $resistance ohms.\n"; $i++; } else { print "That is not a valid answer.\n"; print "Retype your answer.\n"; } }
This is an example of dumb code for me. It calculates voltage, current, or resistance according to Ohm's Law, or the equation Voltage = Current * Resistance. It pretty much is self explanatory for the most part, except for maybe the regexes. Is this good perl code or bad perl code? What makes it good or bad code?

Comment on What makes good Perl code?
Download Code
Re: What makes good Perl code?
by toolic (Chancellor) on Aug 15, 2011 at 20:08 UTC
    That is a subjective question, and the answers will vary greatly based on opinions.

    However, here is my opinion. In general, good code works according to a detailed specification over a wide range of input conditions. In other words, it is free of bugs. How do you know it is free of bugs? You create a comprehensive test suite and run it on multiple platforms/os/perl-versions. How do you know your test suite is comprehensive? You measure code coverage, etc.

    Good code also conforms to standard layout styles. In other words, it looks good and is easy to follow (perltidy).

    Good code is easy to use. It has a good user interface and documentation.

    I have a few comments about your code. It is good that you use the strictures. It is good that you are validating your inputs, though you should do more to prevent common mistakes like div-by-0. Your indentation is good, except I don't like the double-spacing of lines. Your header prints would be less noisy using a HERE-DOC.

    If code is expecting me to enter input from the prompt, I would prefer single-letter response, and make it case-insensitive: v instead of voltage, etc.

    if($calculation =~ /v/i)

    I'm not a fan of the empty elses. I understand why some use them, but I think they add clutter.

    You have some excessive chomping going on:

    my $resistance = <STDIN>; chomp $resistance; print "Now type the voltage of the circuit.\n"; my $voltage = <STDIN>; chomp $voltage; my $current = $voltage / $resistance; chomp $current; # <--------------- NOT NEEDED

    Don't repeat yourself: put the current validation into a sub.

Re: What makes good Perl code?
by hardburn (Abbot) on Aug 15, 2011 at 20:58 UTC

    I've noticed that what a lot programmers think of as "dumb code" is actually a lack of techniques to reduce code duplication. Lambdas are unlikely to meet anybody's definition of "dumb code", but they are a powerful technique for removing redundancy.

    Cleverness as an end to itself shouldn't be done outside of games like Perl Golf. Neither should cleverness be avoided when it helps manage complexity.


    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Re: What makes good Perl code?
by eyepopslikeamosquito (Canon) on Aug 15, 2011 at 21:24 UTC

    the best type of perl code is "dumb code", or code that is very straightforward and almost spells out what you're doing. I was wondering, dumb code is good for Java, but what is the best type of perl code?
    I believe there are a number of fundamentally "good" programming practices that should be followed in both Perl and Java, indeed in most modern programming languages. I wrote these down in On Coding Standards and Code Reviews. The nearest one to your "dumb code" meme is item 4 in the "General Guidelines" section:
    Correctness, simplicity and clarity come first. Avoid unnecessary cleverness.

    While I agree your code is easy to follow, it could be improved in terms of testability, abstraction, encapsulation, and DRY. That is, while this style of coding is fine for short, throw away scripts, it does not scale well to larger systems, which are better designed as a set of loosely coupled, highly cohesive modules, each testable in isolation.

Re: What makes good Perl code?
by davies (Vicar) on Aug 15, 2011 at 21:27 UTC

    I think it's worth quoting the sig of a monk who doesn't post much nowadays:

    My criteria for good software:

    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

    HTML isn't per the original, but it's a language I don't speak. Sorry!

    Regards,

    John Davies

Re: What makes good Perl code?
by perl.j (Pilgrim) on Aug 15, 2011 at 22:32 UTC

    In my opinion, it depends on some "things":

    1. Is someone going to read or edit the code besides you?
    2. Do you need some advanced Perl features that "dumb code" doesn't offer?

    If you said yes to both of these, "dumb code" is not for you. But even if you did say no to some of the questions, I still do not recommend "dumb code" unless the program is extremely simple

    --perl.j
Re: What makes good Perl code?
by Khen1950fx (Canon) on Aug 16, 2011 at 00:31 UTC
    I condensed it a bit. This is closer to how I would do it:
    #!/usr/bin/perl -sl BEGIN { $^W = 1; } sub BEGIN { if ($^W == 1) { print "Let's get started...\n"; } else { die $@; } } use strict; use warnings; use English qw(-no_match_vars); local $OUTPUT_AUTOFLUSH = 1; local $OUTPUT_RECORD_SEPARATOR = *\ ; print "I will calculate whatever \n", "you specify according to\n", "Ohm's law. What shall I\n", "calculate? Type either\n ", "voltage, current, or \n", "resistance.\n"; my $i = 0; while ($i == 0) { my $calculation = <STDIN>; if ($calculation =~ /voltage/) { print "Type the current of the circuit.\n", "Add mA at the end of your answer\n", "if your answer is in milliAmps.\n"; chomp(my $current = <STDIN>); print "Now type the resistance of the circuit.\n"; chomp(my $resistance = <STDIN>); if ($current =~ /mA/) { $current =~ s/mA//; $current =~ s/^\s+//; $current =~ s/ //; $current /= 1000; } else { (); } my $voltage = $current * $resistance; print "Ohm's law is V = IR, so the voltage of\n"; print "the circuit is $voltage volts.\n"; ++$i; } elsif ($calculation =~ /current/) { print "Type the resistance of the circuit.\n"; chomp(my $resistance = <STDIN>); print "Now type the voltage of the circuit.\n"; my $voltage = <STDIN>; my $current = $voltage / $resistance; my $otherCurrent = $current / 1000; print "Ohm's law is V = IR, so the current of\n", "the circuit is $current amps\n", "or $otherCurrent milliAmps.\n"; ++$i; } elsif ($calculation =~ /resistance/) { print "Type the current of the circuit.\n", "Add mA at the end of your answer\n", "if your answer is in milliAmps.\n"; chomp(my $current = <STDIN>); print "Now type the voltage of the circuit\n."; my $voltage = <STDIN>; if ($current =~ /mA/) { $current =~ s/mA//; $current =~ s/^\s+//; $current =~ s/ //; $current /= 1000; } else { (); } my $resistance = $voltage / $current; print "Ohm's law is V = IR, so the resistance of\n", "the circuit is $resistance ohms.\n"; ++$i; } else { print "That is not a valid answer.\n" "Retype your answer.\n"; } }
    Update: made a few additions.
      #!/usr/bin/perl -sl

      The -s switch is used to parse command line switches but your program doesn't use command line switches.

      The -l switch is used to set the Output Record Separator to the same value as the Input Record Separator but later you are explicitly changing the Output Record Separator.

      BEGIN { $^W = 1; } sub BEGIN { if ($^W == 1) { print "Let's get started...\n"; } else { die $@; } }

      Why is this code here?    You turn global warnings on in a BEGIN block.    Why not just use the -w or -W switch?    And why use lexical warnings later as well?    And why die if warnings aren't enabled when you just turned them on?

      local $OUTPUT_RECORD_SEPARATOR = *\ ;

      Why are you assigning the value '*main::\' to $\?

Re: What makes good Perl code?
by Marshall (Prior) on Aug 16, 2011 at 03:03 UTC
    You have asked for an opinion about qualities of good code and for discussion, shown an example of your code. I'm sure that you will get a range of opinions!

    First, double spacing of the code hinders the readability. Judicious application of white space is one of most important things that you can do to increase legibility of your code. Use a blank line to separate "thought units". What constitutes a "thought unit" is subjective and it takes practice to "develop a feel for it".
    BTW: I really like your indenting style - perfect.

    I would for example, single space all of the initial print statements and put a blank line before the i=0; statement, or perhaps like this:

    print "I will calculate whatever\n", "you specify according to\n", "Ohm's law. What shall I\n", "calculate? Type either\n", "voltage, current, or\n", "resistance.\n"; my $i = 0; ....
    Now its easy to see that all those print lines go together as one thing because it is in fact, just one program statement!

    The most serious flaw in the code comes here: "while($i == 0)". On a lab assignment, that certainly could be worth a full grade letter deduction (i.e. max possible grade is now a B). This would be true in Java, C, Perl or whatever.

    This bad loop design error is important. I have to dig around all inside the body of your loop in order to figure out what ends the loop! The condition that ends the loop, whether it is a "for,"while","until" loop should be part of the loop condition in a very direct way. Also, you have a lot of lines between branches of the if{}elsif{}else{}, I would be thinking about subroutines or otherwise compacting things so that the whole "if" statement fits on a single page. "looks good" is another subjective measurement, but aesthetics are important. Perhaps, something like this:

    #!/usr/bin/perl -w use strict; my $line; while( (print "parameter to calculate?:"), ($line=<STDIN>), $line !~ /^\s*q(uit)?\s*$/i) { next if $line =~ /^\s*$/; #blank line => simple re-prompt if ($line =~ /^\s*(resistance|R)\s*$/i) { print "sub to calculate resistance\n"; } elsif ($line =~ /^\s*(voltage|V)\s*$/i) { print "sub to calculate voltage\n"; } elsif ($line =~ /^\s*(current|I)\s*$/i) { print "sub to calculate current\n"; } else { print "illegal entry!\n"; } }
    I did use the comma operator. Some Monks have an aversion to it although I think that it is just fine in the right situation. If you don't like it, just add extra statements as needed. My main point is that "while($i==0)" is not an appropriate loop conditional.

    Standard expected behavior for a command line program:
    - if a mistake is possible, expect that user will do it (maybe unwittingly).
    - allow blanks anywhere on input line (not significant anywhere -> begin, end, middle)
    - blank line is not an error, just re-prompt
    - if there is an error, you have to re-prompt for the user to try again...no getting to question 52 and then blowing up because the user entered "m" for "n"(no)!

    The code as presented is not sufficiently tolerant of the user re-doing errors or detecting errors in the first place. This would be another full letter grade deduction.

    Well written Perl code would take advantage of the language features. Some folks go crazy with super obscure "tricks". That's not necessary. A good understanding of how Perl regex works and the use of list context on the left hand side of an assignment is not considered obscure. For example, here is one regex statement to parse the amps input....not perfect, but it gets "in the ballpark".

    Spaces don't matter. If some text exists past the number, then it must be either "ma" or "mA", "ba" won't work. If $flag_ma is defined, then $amps must also be defined (the division shown will work). If $amps is not defined, then the whole line failed to be valid. Very few statements, but a lot of work is done! As a relative beginner, it might take you some experimentation to figure out how it works, but it should be clear to you what it is supposed to do.

    #!/usr/bin/perl -w use strict; my @tests = ('50 ma', '10ma', '2.3', '-.2 ma', '3.', '4.0', '10ba'); foreach my $input (@tests) { my ($amps, $flag_ma)= $input=~ /^\s*([-+]?\d*\.?\d+)\s*(ma|mA)?\s*$ +/; $amps /=1000 if defined $flag_ma; if (defined $amps) { print "$amps amps\n"; } else { print "$input is an illegal entry\n"; } } __END__ 0.05 amps 0.01 amps 2.3 amps -0.0002 amps 3. is an illegal entry 4.0 amps 10ba is an illegal entry
    Another thing to consider is that this "top down design", "bottom up implementation" idea isn't so "clean". Maybe because regex is so easy with Perl, you might want to consider a different UI if you know the implementation language is Perl. Maybe something like:
    prompt> i = 2.3 prompt> t=3 illegal syntax try again! prompt> r = 3 prompt> v? v=i*r i=2.3 r=3 v=6.9 prompt>v=9 prompt>i? i=v/r r=3 v=9 i=3 prompt>q good bye!
    This is a case where I know that it is easy to keep track of the last thing entered for i,v,r (a hash table). I can parse the input syntax easily with one or two regex'es. So I can make the Perl program a zoomy Ohm's law calculator! And probably use less total lines of code than the "dumb" code while at the same time being compact and easy to understand (if you know regex'es). That's great Perl code, do more with less.

    So one possible coding of an "one page Ohm's Law Calculator". There are just 3 main cases for the "if": (1) set a variable. i=2.3, (2) print a variable. v=?, and (3) wrong syntax.

      Did I mention I'm 12? :-D I actually am 12. I have been going through Sam's teach yourself Perl in 24 hours, and instead of going through the code presented in the book, I look at what it teaches me and use it to make stuff that I will actually use, hence making an Ohm's law calculator. Anyways, thanks for the input! I actually don't know regexes all that well, which I know is a shame, considering regexes are one of the most powerful things about Perl, and in many ways the reason why Perl was made in the first place! I guess I should really go through regexes more. Thanks for the input, again.

        Clinton's book is pretty good, but if you're using the third edition it's showing its age. I wrote a book called Modern Perl which covers Perl 5.12. Electronic versions are free. It might be useful for you.

        That's cool, I started programming when I was 12 too. Now I've got grandchildren older than you and I'm still learning how to program! I mean, I'm already quite good, but it's not something you ever finish, you just stop one day, usually by dying :)

        Since you're focused on accomplishing tasks and seem to have a basic grasp of Perl, I would recommend The Perl Cookbook because it's a collection of solutions to common tasks that come up over and over again.

Re: What makes good Perl code?
by RedElk (Hermit) on Aug 16, 2011 at 04:16 UTC

    Here's a snippet of how I would approach your example in my attempt at "good code". Just another opinion, mind you.

    #!/usr/bin/perl use strict; use warnings; my $voltage; my $current; my $resistance; print "I will calculate whatever you specify according to Ohm's law. What shall I calculate? \n"; menu(); sub menu() { print "\n"; print <<EOF; Press 1 for voltage. Press 2 for current. Press 3 for resistance. Press x to Exit. EOF my $selection = <STDIN>; chomp $selection; if ($selection == 1) {voltage();} elsif ($selection == 2) {current();} elsif ($selection == 3) {resistance();} elsif ($selection =~ /x,X/ {all_done();} else {print "\nSorry, that isn't on the menu. Try again!\n";} menu(); }
Re: What makes good Perl code?
by ambrus (Abbot) on Aug 16, 2011 at 09:32 UTC

    Allow me one minor nitpicking.

    Even if you don't use some more complicated regex like Marshall mentions, instead of writing

    if ($current =~ /mA/) { $current =~ s/mA//; ... }
    it's better to write either
    if ($current =~ s/mA//) { ... }
    or, if you prefer,
    if ($current =~ /mA/) { $current =~ s///; ... }

    This avoids code duplication so now if someone wants to change your program they can't make a mistake like changing only one of the regexps and causing the code to recognize the suffix but not remove it. This isn't too important in this simple case of course.

    PS. yes, I think it's good perl code, except for the too many empty lines.

Re: What makes good Perl code?
by slinky773 (Sexton) on Aug 16, 2011 at 15:41 UTC
    Well, I updated the code a little bit, getting rid of the $i == 0 while loop and other stuff. But don't take my word for it: look at the code!
    #!/usr/bin/perl -w use strict; use warnings; print "I will calculate whatever\n"; print "you specify according to\n"; print "Ohm's law. What shall I\n"; print "calculate? Type either\n"; print "voltage, current, or\n"; print "resistance.\n"; my $calculation = 1; while($calculation) { $calculation = <STDIN>; chomp $calculation; if($calculation =~ m/voltage/) { print "Type the current of the circuit.\n"; print "Add mA at the end of your answer\n"; print "if your answer is in milliAmps.\n"; my $current = <STDIN>; chomp $current; print "Now type the resistance of the circuit.\n"; my $resistance = <STDIN>; chomp $resistance; IF: if($current && $resistance) { if($current =~ m/mA/) { $current =~ s/mA//; $current /= 1000; } else { } } else { print "Those aren't valid answers.\n"; print "Please type that again, will ya?\n"; print "Type the current of the circuit.\n"; print "Add mA at the end of your answer\n"; print "if your answer is in milliAmps.\n"; $current = <STDIN>; chomp $current; print "Now type the resistance of the circuit.\n"; $resistance = <STDIN>; chomp $resistance; goto IF; } my $voltage = $current * $resistance; print "Ohm's law is V = IR, so the voltage of\n"; print "the circuit is $voltage volts.\n"; $calculation = 0; } elsif($calculation =~ m/current/) { print "Type the resistance of the circuit.\n"; my $resistance = <STDIN>; chomp $resistance; print "Now type the voltage of the circuit.\n"; my $voltage = <STDIN>; chomp $voltage; IF: if($resistance && $voltage) { } else { print "That is not a valid answer.\n"; print "Please type that again, will ya?\n"; print "Type the voltage of the circuit.\n"; $resistance = <STDIN>; chomp $resistance; print "Now type the voltage of the circuit.\n"; $voltage = <STDIN>; chomp $voltage; goto IF; } my $current = $voltage / $resistance; my $otherCurrent = $current / 1000; print "Ohm's law is V = IR, so the current of\n"; print "the circuit is $current amps,\n"; print "or $otherCurrent milliAmps.\n"; $calculation = 0; } elsif($calculation =~ m/resistance/) { print "Type the current of the circuit.\n"; print "Add mA at the end of your answer\n"; print "if your answer is in milliAmps.\n"; my $current = <STDIN>; chomp $current; print "Now type the voltage of the circuit.\n"; my $voltage = <STDIN>; chomp $voltage; IF: if($current && $voltage) { if($current =~ m/mA/) { $current =~ s/mA//; $current /= 1000; } else { } } else { print "Those aren't valid answers.\n"; print "Please type that again, will ya?\n"; print "Type the current of the circuit.\n"; print "Add mA at the end of your answer\n"; print "if your answer is in milliAmps.\n"; $current = <STDIN>; chomp $current; print "Now type the voltage of the circuit.\n"; $voltage = <STDIN>; chomp $voltage; goto IF; } my $resistance = $voltage / $current; print "Ohm's law is V = IR, so the resistance of\n"; print "the circuit is $resistance ohms.\n"; $calculation = 0; } else { print "That is not a valid answer.\n"; print "Retype your answer.\n"; } }
      I also condensed the if($current =~ m/mA/) stuff into this:
      if($current =~ s/mA//i) { $current /= 1000; }
      and put that everywhere it was in use.
      I was thinking about what Marshall said about user input, and how the program should be tolerant of user input no matter what it is. I was looking for a way to change this:
      IF: if($current && $resistance) { if($current =~ s/mA//i) { $current /= 1000; } else { } } else { print "Those aren't valid answers.\n"; print "Please type that again, will ya?\n"; print "Type the current of the circuit.\n"; print "Add mA at the end of your answer\n"; print "if your answer is in milliAmps.\n"; $current = <STDIN>; chomp $current; print "Now type the resistance of the circuit.\n"; $resistance = <STDIN>; chomp $resistance; goto IF; }
      I want a way for the else block to run if both the inputs don't have numbers in them. Perhaps with an elsif block? However, I'm not aware of anything that would do what I require. Maybe with an algorithm? I don't know of ANY algorithms at all except for the Fischer-Yates shuffle, and that's pretty useless nowadays, considering Perl has a shuffle command anyways. Anyone know of a way to test for a number in a variable?

        One thing I do is to cleanup bulky lines after I get it working. For example, I might use $LOOP = $LOOP +1; until I get comfy and then go back and change that to ++$LOOP;.

        In this case, the first thing I noticed was chomp: chomp (my $current = <STDIN>);.

        Also, I keep the input and descriptor together.

        print "Type the current of the circuit.\n"; chomp (my $current = <STDIN>); print "Now type the resistance of the circuit.\n"; chomp (my $resistance = <STDIN>);

        But, really, as long as it's legible and someone can pick this up after you've moved on and edit/use it, you're a step above some people. Keep It Simple, =!Sloppy.

Re: What makes good Perl code?
by pvaldes (Chaplain) on Aug 17, 2011 at 09:46 UTC
    Just my 2 cents, I'm sure it can be improved a lot. I simply found that is more readable like this... and at least is a little more compact.
    #!/usr/bin/perl -w use strict; use warnings; use feature qw(say); use English qw(-no_match_vars); BEGIN { $^W = 1; } sub BEGIN { if ($^W == 1) {say "Let's get started..."} else {die $@} } local $OUTPUT_AUTOFLUSH = 1; local $OUTPUT_RECORD_SEPARATOR = *\ ; print <<NOTE_ONE; I will calculate whatever you specify according to Ohm's law. What shall I calculate? Type either voltage, current, or resistance NOTE_ONE my $type_current = <<NOTE_TWO; Type the current of the circuit. Add mA at the end of your answer, if your answer is in milliAmps: NOTE_TWO my $type_voltage = "Now type the voltage of the circuit:"; my $type_resistance = "Type the resistance of the circuit:"; my $ohmlaw = "Ohm's law is V = IR, so "; my $i = 0; while ($i == 0) { my $calculation = <STDIN>; if ($calculation =~ /voltage/) { say $type_current; my $current = <STDIN>; say $type_resistance; my $resistance = <STDIN>; if ($current =~ /mA/) { $current =~ s/mA//; $current =~ s/(^\s+| )//; $current /= 1000; } else {()} say $ohmlaw . "the voltage of\nthe circuit is " . $current * $ +resistance . " volts."; ++$i; } elsif ($calculation =~ /current/) { say $type_resistance; my $resistance = <STDIN>; say $type_voltage; my $voltage = <STDIN>; say $ohmlaw . "the current of\nthe circuit is ". $voltage / $r +esistance . " amps., or " . $voltage /($resistance*1000) . " milliAmp +s."; ++$i; } elsif ($calculation =~ /resistance/) { say $type_current; my $current = <STDIN>; say $type_voltage; my $voltage = <STDIN>; if ($current =~ /mA/) { $current =~ s/mA//; $current =~ s/(^\s+| )//; $current /= 1000; } else {()} say $ohmlaw ."the resistance of\nthe circuit is ". $voltage / +$current . "ohms."; ++$i; } else {say "That is not a valid answer.\nRetype your answer."} }
      #!/usr/bin/perl -w ... use warnings; ... BEGIN { $^W = 1; } sub BEGIN { if ($^W == 1) {say "Let's get started..."} else {die $@} }

      Why do you want to turn on warnings 3 times and then die if they're not turned on? use warnings; is sufficient for anything but an ancient version of perl, in which case you might need the -w switch.

      my $resistance = <STDIN>; if ($current =~ /mA/) { $current =~ s/mA//; $current =~ s/(^\s+| )//; $current /= 1000; }

      That's kind of a mess. First you match on mA and then remove mA, not to mention that it will fail on bad input. Consider an answer like 0 or "more amps than you'll ever know!" It's much better to extract the expected input and complain if you can't find it. The following is a quick, untested example...

      my $input = <STDIN>; my ($current) = $input =~ /^\s*[\d.]+\s+/ or do { error_stuff(); ... # next, redo, or return, as appropriate }; $input =~ /\s+mA\s*$/ and $current /= 1000;

        Gah, I'm an idiot...

        my ($current) = $input =~ /^\s*[\d.]+\s+/ or do {

        should be

        my ($current) = $input =~ /^\s*([\d.]+)\s+/ or do {

        or there won't be a capture of the number.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://920343]
Approved by toolic
Front-paged by planetscape
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (10)
As of 2014-09-22 15:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (198 votes), past polls