Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Collect prints to a string

by InfiniteSilence (Curate)
on Apr 23, 2011 at 17:58 UTC ( #900989=note: print w/replies, xml ) Need Help??

in reply to Collect prints to a string

  • Step 1: Learn to write tests in Perl and create a separate test for every function that you plan to modify. Make certain that all tests pass 100% before proceeding. [ Contextual note: I add this because, when making changes to production code, you can avoid the fear of breaking things by having comprehensive testing available to run automated regression tests. Once you get used to doing this you will lose your fear of refactoring production code.]
  • Step 2: Change the offending function names by appending something to them. So sub print_l becomes sub print_l_old. Change the 'print' statements to 'return' statements. Rerun your tests. Everything should break (that's okay for now).
  • Step 3: Create new functions with the old function names and have them call the old functions like this:
    use strict; sub print_l_old { return qq|the world is a great place|; } sub print_l{ print print_l_old() . qq| to be.|; } print_l();
The idea of a function is normally to return something. In other languages there is a way to notify the user whether or not a function was supposed to be used to return anything (like declaring it void, etc.). There is not anything like this in Perl (that I know of) so my best practice is to almost always write functions to return something, even if that something is only undef. Whatever solution you come up with, I would add it to your coding standards. I added this section and all this help about refactoring because I think the code you have posted probably needs to be rewritten. There are good, safe ways to do that using Perl utilities.

Update: Oops, I forgot to mention that your tests will break if you add new stuff like  qq| to be.|. The right approach should be to just call the old functions in the new without appending anything and rerun your tests. They should all pass. Then rewrite your tests to match your next version's changes. You should be using a version control system, so you should be able to easily differentiate versions and tag releases along with associated tests.

Celebrate Intellectual Diversity

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://900989]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2017-05-29 07:05 GMT
Find Nodes?
    Voting Booth?