Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Suggestion on rewriting small code

by Anonymous Monk
on Aug 21, 2019 at 10:03 UTC ( #11104795=note: print w/replies, xml ) Need Help??


in reply to Suggestion on rewriting small code

There is no need for flags and counters. It's just making it too complicated. Here is a simple way to do it. First initialize the string to a quote, because you want to start with a quote. then foreach number, add on a job string with the pipes after. once yore done, chop off the last three characters because you don't want two pipes and a space on the end. and put everything in a subroutine so that you aren't just using global variables all over the place.
#!/usr/bin/env perl use strict; use warnings; use feature 'say'; run(); sub run { my @arr = (12341,1245125,1525125,125125125); my $str = '"'; foreach my $num (@arr) { $str .= "job==$num || "; } chop $str; chop $str; chop $str; $str .= '"'; say $str; return $str; }

Replies are listed 'Best First'.
Re^2: Suggestion on rewriting small code
by Anonymous Monk on Aug 21, 2019 at 12:30 UTC
    No you're making it too complicated! :-)

    The first problem is initializing the string with that quote.

    That causes the next, of concat in a loop, leaving crud at the end of the string.

    The dominoes continue to fall as ya chop chop chop away the first two mistakes.

    Finally, having to add a quote to the end of a sting is a bad sign that something went wrong earlier, which is now being hacked into compliance.

    Also you should know that printing from inside subs is a bad habit, but don't ask me how I know. It just quickly leads to layers of confusion. May I suggest:

    say run(); sub run { my @arr = (12341,1245125,1525125,125125125); my $str = join '', '"', (join ' || ', map {"job==$_"} @arr), '"'; return $str }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11104795]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2019-09-20 19:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The room is dark, and your next move is ...












    Results (268 votes). Check out past polls.

    Notices?