http://www.perlmonks.org?node_id=11104795


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 }