I don't have anything to add regarding functionality, but I've got a few ideas for readability.

First thing I'd do is change this:

# $d as data # $mbc as ModBusControl # $r as response my ( $d, $mbc, $r )=( shift, MBclient->new(), undef );

...to this:

my $data = shift; my $mod_bus_control = MBClient->new; my $response = undef;

...and then rename all the variables below this code to the proper names. It's difficult to have to scroll through code to find the legend of what the variable $r stands for, and I guarantee you'll forget in three months when you're trying to do more work on your code. You could have $r in this sub meaning one thing, and in other subs, something totally different. Just use the real names.

Also, remove most of the comment lines. There's no need to say something like # read... or # return... when the next line below are read_input_registers and return($r). In almost all cases, the code speaks for itself. If you want a piece to stand out (like a return), separate it with whitespace on the lines above and below.

UPDATE: I'd also change this:

$mbc->host ( $d->{ip} ); $mbc->port ( $d->{port} ); $mbc->unit_id ( 0 );

...to this:

$mbc->host( $d->{ip} ); $mbc->port( $d->{port} ); $mbc->unit_id( 0 );

I had to do a double-take to realize those were method calls with params, with the parens so far away. Parens should be right next to the function name. The whitespace *inside* of the parens is personal preference though. Depending on the situation, I use whitespace between the parens and params, and most of the times not.

-stevieb


In reply to Re: Way to make this code better. by stevieb
in thread Way to make this code better. by builat

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.