How to print comma “,” in the middle of sentenced when necessary, Part 1, Perl












1














I need to print comma "," when the list more than one, and if more than one, the last list I don't want to print comma. I know I can use Join to to do this but I can't loop @NAMES with comma if there is another @FAMILIES to add in.



#!/usr/bin/perl
use strict;
use warnings;

my @NAMES = qw(ALLIES BOBBY CAKRA);
my @FAMILIES = qw(A B C);


foreach my $names (@NAMES)
{
foreach my $families (@FAMILIES)
{
print "$names, // $familiesn";
}
}


Expected Outcome:



ALLIES, // A
ALLIES, // B
ALLIES, // C
BOBBY, // A
BOBBY, // B
BOBBY, // C
CAKRA, // A
CAKRA, // B
CAKRA // C









share|improve this question
























  • @Shawn, yes. The code I shown you will permanently print the comma "," , I know I can use join ( "," ) but I can't figured it out.
    – Danial Haris
    Nov 13 '18 at 3:14
















1














I need to print comma "," when the list more than one, and if more than one, the last list I don't want to print comma. I know I can use Join to to do this but I can't loop @NAMES with comma if there is another @FAMILIES to add in.



#!/usr/bin/perl
use strict;
use warnings;

my @NAMES = qw(ALLIES BOBBY CAKRA);
my @FAMILIES = qw(A B C);


foreach my $names (@NAMES)
{
foreach my $families (@FAMILIES)
{
print "$names, // $familiesn";
}
}


Expected Outcome:



ALLIES, // A
ALLIES, // B
ALLIES, // C
BOBBY, // A
BOBBY, // B
BOBBY, // C
CAKRA, // A
CAKRA, // B
CAKRA // C









share|improve this question
























  • @Shawn, yes. The code I shown you will permanently print the comma "," , I know I can use join ( "," ) but I can't figured it out.
    – Danial Haris
    Nov 13 '18 at 3:14














1












1








1







I need to print comma "," when the list more than one, and if more than one, the last list I don't want to print comma. I know I can use Join to to do this but I can't loop @NAMES with comma if there is another @FAMILIES to add in.



#!/usr/bin/perl
use strict;
use warnings;

my @NAMES = qw(ALLIES BOBBY CAKRA);
my @FAMILIES = qw(A B C);


foreach my $names (@NAMES)
{
foreach my $families (@FAMILIES)
{
print "$names, // $familiesn";
}
}


Expected Outcome:



ALLIES, // A
ALLIES, // B
ALLIES, // C
BOBBY, // A
BOBBY, // B
BOBBY, // C
CAKRA, // A
CAKRA, // B
CAKRA // C









share|improve this question















I need to print comma "," when the list more than one, and if more than one, the last list I don't want to print comma. I know I can use Join to to do this but I can't loop @NAMES with comma if there is another @FAMILIES to add in.



#!/usr/bin/perl
use strict;
use warnings;

my @NAMES = qw(ALLIES BOBBY CAKRA);
my @FAMILIES = qw(A B C);


foreach my $names (@NAMES)
{
foreach my $families (@FAMILIES)
{
print "$names, // $familiesn";
}
}


Expected Outcome:



ALLIES, // A
ALLIES, // B
ALLIES, // C
BOBBY, // A
BOBBY, // B
BOBBY, // C
CAKRA, // A
CAKRA, // B
CAKRA // C






perl






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 9:24







Danial Haris

















asked Nov 13 '18 at 2:53









Danial HarisDanial Haris

345




345












  • @Shawn, yes. The code I shown you will permanently print the comma "," , I know I can use join ( "," ) but I can't figured it out.
    – Danial Haris
    Nov 13 '18 at 3:14


















  • @Shawn, yes. The code I shown you will permanently print the comma "," , I know I can use join ( "," ) but I can't figured it out.
    – Danial Haris
    Nov 13 '18 at 3:14
















@Shawn, yes. The code I shown you will permanently print the comma "," , I know I can use join ( "," ) but I can't figured it out.
– Danial Haris
Nov 13 '18 at 3:14




@Shawn, yes. The code I shown you will permanently print the comma "," , I know I can use join ( "," ) but I can't figured it out.
– Danial Haris
Nov 13 '18 at 3:14












5 Answers
5






active

oldest

votes


















2














I don't see that there is an elegant and clean way since you need to drop the comma on the last element of both arrays. Then add an explicit condition, while iterating over indices so to be able to single out the last elements



use warnings;
use strict;
use feature 'say';

my @names = qw(ALLIES BOBBY CAKRA);
my @families = qw(A B C);

for my $n (0..$#names) {
for my $f (0..$#families) {
say $names[$n],
( ($n == $#names and $f == $#families) ? ' // ' : ', // '),
$families[$f];
}
}


The parenthesis in the condition of the ternary operator ( ? : ) are needed for precedence. Another way is to use && instead of and, which binds more tightly, but I didn't want the code to rely on
a specific operator.



The syntax $#ary is for the index of the last element of @ary.






share|improve this answer





















  • how about if I use hash? How can I iterate like what I use in array? - the question is updated
    – Danial Haris
    Nov 13 '18 at 8:27










  • @Danial Haris, @names = keys(%h); @families = values(%h);
    – ikegami
    Nov 13 '18 at 13:41










  • @ikegami, I can't use arrays or turn it into arrays from hash because I have sorted the data in a multidimensional hash. Do we have a way to do like array does? like $array[0], something like this because I have already tied the hash, so the order will be in place now?
    – Danial Haris
    Nov 14 '18 at 4:14








  • 1




    $hash{ (keys(%hash))[0] }, but calling keys like this repeatedly would be very inefficient compared to $hash{ $names[0] } as in zdim's code
    – ikegami
    Nov 14 '18 at 10:47








  • 1




    @DanialHaris I was away for a while, just now could read these comments. I'll look at it tonight
    – zdim
    Nov 15 '18 at 0:26



















1














Special casing the last element is always messy, there are a bunch of trade offs, you just end up choosing which one looks less bad to you.



Another option compared to @zdim's perfectly good solution.



Note that I'm going to change @names and @families during execution, more tradeoffs, copying the array is the easy fix if it is a problem.



#!/usr/bin/perl
use strict;
use warnings;

my @names = qw(ALLIES BOBBY CAKRA);
my @families = qw(A B C);

my $last_name = pop(@names);

foreach my $names (@names)
{
foreach my $families (@families)
{
print "$names, // $familiesn";
}
}

my $last_family = pop(@families);

foreach my $families (@families)
{
print "$last_name, // $familiesn";
}

print "$last_name // $last_familyn";





share|improve this answer





















  • Handles empty @names and/or empty @families "poorly".
    – ikegami
    Nov 13 '18 at 13:27





















1














Using join would generally be the best answer, but that would only work if you want to prevent a comma at the end of the line. (At least for a straight-forward answer, I'm sure you could hack it.)



You can make use of Perl's $#array_name variables inside a for loop to check when you're at the end of both lists, like so:



#!/usr/bin/perl
use strict;
use warnings;


my @names = qw(ALLIES BOBBY CAKRA);
my @families = qw(A B C);

for my $i (0..$#names) {
for my $j (0..$#families) {
print "$names[$i]" . ($i == $#names && $j == $#families ? ' ' : ', ') . "// $families[$j]n";
}
}


Also, a just a note on style: the Perl Style Guide (try perldoc perlstyle) recommends using all-capital variable names only when they're constants. It's not a big deal, and definitely not required, but it can make it a little easier for others to follow your code. :)






share|improve this answer































    1














    The alternative is to separate the output from the cross-product generation, and handling the last cast specially.



    my @cross_product;
    for my $n (0..$#names) {
    for my $f (0..$#families) {
    push @cross_product, [ $n, $f ];
    }
    }

    if (@cross_product) {
    say "$_->[0], // $_->[1]" for @cross_product[0..@cross_product-2];
    say "$_->[0] // $_->[1]" for $cross_product[-1];
    }


    You can even avoid using up any memory as follows:



    use Set::CrossProduct qw( );

    my $i = Set::CrossProduct->new([ @names, @families ]);
    my $N = $i->cardinality;
    say sprintf '%1$s%3$s // %2$d', $i->get(), $_?',':'' for -$N+1..0;





    share|improve this answer































      1














      I thought of a variation to ikegami's (storing the results in a temporary array). There would be too many changes to comfortably fit in a comment, so here:



      You could store the comma to the temporary list, too, and then remove it from only the last line.



      #!/usr/bin/perl
      use strict;
      use warnings;

      my @names = qw(ALLIES BOBBY CAKRA);
      my @families = qw(A B C);
      my @output_lines;

      foreach my $name (@names) {
      foreach my $family (@families) {
      push @output_lines, [$name, ',', ' // ' . $family . "n"];
      }
      }

      if (@output_lines) {
      $output_lines[-1][1] = ''; # remove comma from last line
      print map { @$_ } @output_lines;
      }





      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53273095%2fhow-to-print-comma-in-the-middle-of-sentenced-when-necessary-part-1-perl%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        I don't see that there is an elegant and clean way since you need to drop the comma on the last element of both arrays. Then add an explicit condition, while iterating over indices so to be able to single out the last elements



        use warnings;
        use strict;
        use feature 'say';

        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        for my $n (0..$#names) {
        for my $f (0..$#families) {
        say $names[$n],
        ( ($n == $#names and $f == $#families) ? ' // ' : ', // '),
        $families[$f];
        }
        }


        The parenthesis in the condition of the ternary operator ( ? : ) are needed for precedence. Another way is to use && instead of and, which binds more tightly, but I didn't want the code to rely on
        a specific operator.



        The syntax $#ary is for the index of the last element of @ary.






        share|improve this answer





















        • how about if I use hash? How can I iterate like what I use in array? - the question is updated
          – Danial Haris
          Nov 13 '18 at 8:27










        • @Danial Haris, @names = keys(%h); @families = values(%h);
          – ikegami
          Nov 13 '18 at 13:41










        • @ikegami, I can't use arrays or turn it into arrays from hash because I have sorted the data in a multidimensional hash. Do we have a way to do like array does? like $array[0], something like this because I have already tied the hash, so the order will be in place now?
          – Danial Haris
          Nov 14 '18 at 4:14








        • 1




          $hash{ (keys(%hash))[0] }, but calling keys like this repeatedly would be very inefficient compared to $hash{ $names[0] } as in zdim's code
          – ikegami
          Nov 14 '18 at 10:47








        • 1




          @DanialHaris I was away for a while, just now could read these comments. I'll look at it tonight
          – zdim
          Nov 15 '18 at 0:26
















        2














        I don't see that there is an elegant and clean way since you need to drop the comma on the last element of both arrays. Then add an explicit condition, while iterating over indices so to be able to single out the last elements



        use warnings;
        use strict;
        use feature 'say';

        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        for my $n (0..$#names) {
        for my $f (0..$#families) {
        say $names[$n],
        ( ($n == $#names and $f == $#families) ? ' // ' : ', // '),
        $families[$f];
        }
        }


        The parenthesis in the condition of the ternary operator ( ? : ) are needed for precedence. Another way is to use && instead of and, which binds more tightly, but I didn't want the code to rely on
        a specific operator.



        The syntax $#ary is for the index of the last element of @ary.






        share|improve this answer





















        • how about if I use hash? How can I iterate like what I use in array? - the question is updated
          – Danial Haris
          Nov 13 '18 at 8:27










        • @Danial Haris, @names = keys(%h); @families = values(%h);
          – ikegami
          Nov 13 '18 at 13:41










        • @ikegami, I can't use arrays or turn it into arrays from hash because I have sorted the data in a multidimensional hash. Do we have a way to do like array does? like $array[0], something like this because I have already tied the hash, so the order will be in place now?
          – Danial Haris
          Nov 14 '18 at 4:14








        • 1




          $hash{ (keys(%hash))[0] }, but calling keys like this repeatedly would be very inefficient compared to $hash{ $names[0] } as in zdim's code
          – ikegami
          Nov 14 '18 at 10:47








        • 1




          @DanialHaris I was away for a while, just now could read these comments. I'll look at it tonight
          – zdim
          Nov 15 '18 at 0:26














        2












        2








        2






        I don't see that there is an elegant and clean way since you need to drop the comma on the last element of both arrays. Then add an explicit condition, while iterating over indices so to be able to single out the last elements



        use warnings;
        use strict;
        use feature 'say';

        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        for my $n (0..$#names) {
        for my $f (0..$#families) {
        say $names[$n],
        ( ($n == $#names and $f == $#families) ? ' // ' : ', // '),
        $families[$f];
        }
        }


        The parenthesis in the condition of the ternary operator ( ? : ) are needed for precedence. Another way is to use && instead of and, which binds more tightly, but I didn't want the code to rely on
        a specific operator.



        The syntax $#ary is for the index of the last element of @ary.






        share|improve this answer












        I don't see that there is an elegant and clean way since you need to drop the comma on the last element of both arrays. Then add an explicit condition, while iterating over indices so to be able to single out the last elements



        use warnings;
        use strict;
        use feature 'say';

        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        for my $n (0..$#names) {
        for my $f (0..$#families) {
        say $names[$n],
        ( ($n == $#names and $f == $#families) ? ' // ' : ', // '),
        $families[$f];
        }
        }


        The parenthesis in the condition of the ternary operator ( ? : ) are needed for precedence. Another way is to use && instead of and, which binds more tightly, but I didn't want the code to rely on
        a specific operator.



        The syntax $#ary is for the index of the last element of @ary.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 '18 at 4:02









        zdimzdim

        31.9k32041




        31.9k32041












        • how about if I use hash? How can I iterate like what I use in array? - the question is updated
          – Danial Haris
          Nov 13 '18 at 8:27










        • @Danial Haris, @names = keys(%h); @families = values(%h);
          – ikegami
          Nov 13 '18 at 13:41










        • @ikegami, I can't use arrays or turn it into arrays from hash because I have sorted the data in a multidimensional hash. Do we have a way to do like array does? like $array[0], something like this because I have already tied the hash, so the order will be in place now?
          – Danial Haris
          Nov 14 '18 at 4:14








        • 1




          $hash{ (keys(%hash))[0] }, but calling keys like this repeatedly would be very inefficient compared to $hash{ $names[0] } as in zdim's code
          – ikegami
          Nov 14 '18 at 10:47








        • 1




          @DanialHaris I was away for a while, just now could read these comments. I'll look at it tonight
          – zdim
          Nov 15 '18 at 0:26


















        • how about if I use hash? How can I iterate like what I use in array? - the question is updated
          – Danial Haris
          Nov 13 '18 at 8:27










        • @Danial Haris, @names = keys(%h); @families = values(%h);
          – ikegami
          Nov 13 '18 at 13:41










        • @ikegami, I can't use arrays or turn it into arrays from hash because I have sorted the data in a multidimensional hash. Do we have a way to do like array does? like $array[0], something like this because I have already tied the hash, so the order will be in place now?
          – Danial Haris
          Nov 14 '18 at 4:14








        • 1




          $hash{ (keys(%hash))[0] }, but calling keys like this repeatedly would be very inefficient compared to $hash{ $names[0] } as in zdim's code
          – ikegami
          Nov 14 '18 at 10:47








        • 1




          @DanialHaris I was away for a while, just now could read these comments. I'll look at it tonight
          – zdim
          Nov 15 '18 at 0:26
















        how about if I use hash? How can I iterate like what I use in array? - the question is updated
        – Danial Haris
        Nov 13 '18 at 8:27




        how about if I use hash? How can I iterate like what I use in array? - the question is updated
        – Danial Haris
        Nov 13 '18 at 8:27












        @Danial Haris, @names = keys(%h); @families = values(%h);
        – ikegami
        Nov 13 '18 at 13:41




        @Danial Haris, @names = keys(%h); @families = values(%h);
        – ikegami
        Nov 13 '18 at 13:41












        @ikegami, I can't use arrays or turn it into arrays from hash because I have sorted the data in a multidimensional hash. Do we have a way to do like array does? like $array[0], something like this because I have already tied the hash, so the order will be in place now?
        – Danial Haris
        Nov 14 '18 at 4:14






        @ikegami, I can't use arrays or turn it into arrays from hash because I have sorted the data in a multidimensional hash. Do we have a way to do like array does? like $array[0], something like this because I have already tied the hash, so the order will be in place now?
        – Danial Haris
        Nov 14 '18 at 4:14






        1




        1




        $hash{ (keys(%hash))[0] }, but calling keys like this repeatedly would be very inefficient compared to $hash{ $names[0] } as in zdim's code
        – ikegami
        Nov 14 '18 at 10:47






        $hash{ (keys(%hash))[0] }, but calling keys like this repeatedly would be very inefficient compared to $hash{ $names[0] } as in zdim's code
        – ikegami
        Nov 14 '18 at 10:47






        1




        1




        @DanialHaris I was away for a while, just now could read these comments. I'll look at it tonight
        – zdim
        Nov 15 '18 at 0:26




        @DanialHaris I was away for a while, just now could read these comments. I'll look at it tonight
        – zdim
        Nov 15 '18 at 0:26













        1














        Special casing the last element is always messy, there are a bunch of trade offs, you just end up choosing which one looks less bad to you.



        Another option compared to @zdim's perfectly good solution.



        Note that I'm going to change @names and @families during execution, more tradeoffs, copying the array is the easy fix if it is a problem.



        #!/usr/bin/perl
        use strict;
        use warnings;

        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        my $last_name = pop(@names);

        foreach my $names (@names)
        {
        foreach my $families (@families)
        {
        print "$names, // $familiesn";
        }
        }

        my $last_family = pop(@families);

        foreach my $families (@families)
        {
        print "$last_name, // $familiesn";
        }

        print "$last_name // $last_familyn";





        share|improve this answer





















        • Handles empty @names and/or empty @families "poorly".
          – ikegami
          Nov 13 '18 at 13:27


















        1














        Special casing the last element is always messy, there are a bunch of trade offs, you just end up choosing which one looks less bad to you.



        Another option compared to @zdim's perfectly good solution.



        Note that I'm going to change @names and @families during execution, more tradeoffs, copying the array is the easy fix if it is a problem.



        #!/usr/bin/perl
        use strict;
        use warnings;

        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        my $last_name = pop(@names);

        foreach my $names (@names)
        {
        foreach my $families (@families)
        {
        print "$names, // $familiesn";
        }
        }

        my $last_family = pop(@families);

        foreach my $families (@families)
        {
        print "$last_name, // $familiesn";
        }

        print "$last_name // $last_familyn";





        share|improve this answer





















        • Handles empty @names and/or empty @families "poorly".
          – ikegami
          Nov 13 '18 at 13:27
















        1












        1








        1






        Special casing the last element is always messy, there are a bunch of trade offs, you just end up choosing which one looks less bad to you.



        Another option compared to @zdim's perfectly good solution.



        Note that I'm going to change @names and @families during execution, more tradeoffs, copying the array is the easy fix if it is a problem.



        #!/usr/bin/perl
        use strict;
        use warnings;

        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        my $last_name = pop(@names);

        foreach my $names (@names)
        {
        foreach my $families (@families)
        {
        print "$names, // $familiesn";
        }
        }

        my $last_family = pop(@families);

        foreach my $families (@families)
        {
        print "$last_name, // $familiesn";
        }

        print "$last_name // $last_familyn";





        share|improve this answer












        Special casing the last element is always messy, there are a bunch of trade offs, you just end up choosing which one looks less bad to you.



        Another option compared to @zdim's perfectly good solution.



        Note that I'm going to change @names and @families during execution, more tradeoffs, copying the array is the easy fix if it is a problem.



        #!/usr/bin/perl
        use strict;
        use warnings;

        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        my $last_name = pop(@names);

        foreach my $names (@names)
        {
        foreach my $families (@families)
        {
        print "$names, // $familiesn";
        }
        }

        my $last_family = pop(@families);

        foreach my $families (@families)
        {
        print "$last_name, // $familiesn";
        }

        print "$last_name // $last_familyn";






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 '18 at 4:48









        lodlod

        923612




        923612












        • Handles empty @names and/or empty @families "poorly".
          – ikegami
          Nov 13 '18 at 13:27




















        • Handles empty @names and/or empty @families "poorly".
          – ikegami
          Nov 13 '18 at 13:27


















        Handles empty @names and/or empty @families "poorly".
        – ikegami
        Nov 13 '18 at 13:27






        Handles empty @names and/or empty @families "poorly".
        – ikegami
        Nov 13 '18 at 13:27













        1














        Using join would generally be the best answer, but that would only work if you want to prevent a comma at the end of the line. (At least for a straight-forward answer, I'm sure you could hack it.)



        You can make use of Perl's $#array_name variables inside a for loop to check when you're at the end of both lists, like so:



        #!/usr/bin/perl
        use strict;
        use warnings;


        my @names = qw(ALLIES BOBBY CAKRA);
        my @families = qw(A B C);

        for my $i (0..$#names) {
        for my $j (0..$#families) {
        print "$names[$i]" . ($i == $#names && $j == $#families ? ' ' : ', ') . "// $families[$j]n";
        }
        }


        Also, a just a note on style: the Perl Style Guide (try perldoc perlstyle) recommends using all-capital variable names only when they're constants. It's not a big deal, and definitely not required, but it can make it a little easier for others to follow your code. :)






        share|improve this answer




























          1














          Using join would generally be the best answer, but that would only work if you want to prevent a comma at the end of the line. (At least for a straight-forward answer, I'm sure you could hack it.)



          You can make use of Perl's $#array_name variables inside a for loop to check when you're at the end of both lists, like so:



          #!/usr/bin/perl
          use strict;
          use warnings;


          my @names = qw(ALLIES BOBBY CAKRA);
          my @families = qw(A B C);

          for my $i (0..$#names) {
          for my $j (0..$#families) {
          print "$names[$i]" . ($i == $#names && $j == $#families ? ' ' : ', ') . "// $families[$j]n";
          }
          }


          Also, a just a note on style: the Perl Style Guide (try perldoc perlstyle) recommends using all-capital variable names only when they're constants. It's not a big deal, and definitely not required, but it can make it a little easier for others to follow your code. :)






          share|improve this answer


























            1












            1








            1






            Using join would generally be the best answer, but that would only work if you want to prevent a comma at the end of the line. (At least for a straight-forward answer, I'm sure you could hack it.)



            You can make use of Perl's $#array_name variables inside a for loop to check when you're at the end of both lists, like so:



            #!/usr/bin/perl
            use strict;
            use warnings;


            my @names = qw(ALLIES BOBBY CAKRA);
            my @families = qw(A B C);

            for my $i (0..$#names) {
            for my $j (0..$#families) {
            print "$names[$i]" . ($i == $#names && $j == $#families ? ' ' : ', ') . "// $families[$j]n";
            }
            }


            Also, a just a note on style: the Perl Style Guide (try perldoc perlstyle) recommends using all-capital variable names only when they're constants. It's not a big deal, and definitely not required, but it can make it a little easier for others to follow your code. :)






            share|improve this answer














            Using join would generally be the best answer, but that would only work if you want to prevent a comma at the end of the line. (At least for a straight-forward answer, I'm sure you could hack it.)



            You can make use of Perl's $#array_name variables inside a for loop to check when you're at the end of both lists, like so:



            #!/usr/bin/perl
            use strict;
            use warnings;


            my @names = qw(ALLIES BOBBY CAKRA);
            my @families = qw(A B C);

            for my $i (0..$#names) {
            for my $j (0..$#families) {
            print "$names[$i]" . ($i == $#names && $j == $#families ? ' ' : ', ') . "// $families[$j]n";
            }
            }


            Also, a just a note on style: the Perl Style Guide (try perldoc perlstyle) recommends using all-capital variable names only when they're constants. It's not a big deal, and definitely not required, but it can make it a little easier for others to follow your code. :)







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 13 '18 at 6:11









            Gerhard Barnard

            6,92831131




            6,92831131










            answered Nov 13 '18 at 4:02









            Ashton WiersdorfAshton Wiersdorf

            567417




            567417























                1














                The alternative is to separate the output from the cross-product generation, and handling the last cast specially.



                my @cross_product;
                for my $n (0..$#names) {
                for my $f (0..$#families) {
                push @cross_product, [ $n, $f ];
                }
                }

                if (@cross_product) {
                say "$_->[0], // $_->[1]" for @cross_product[0..@cross_product-2];
                say "$_->[0] // $_->[1]" for $cross_product[-1];
                }


                You can even avoid using up any memory as follows:



                use Set::CrossProduct qw( );

                my $i = Set::CrossProduct->new([ @names, @families ]);
                my $N = $i->cardinality;
                say sprintf '%1$s%3$s // %2$d', $i->get(), $_?',':'' for -$N+1..0;





                share|improve this answer




























                  1














                  The alternative is to separate the output from the cross-product generation, and handling the last cast specially.



                  my @cross_product;
                  for my $n (0..$#names) {
                  for my $f (0..$#families) {
                  push @cross_product, [ $n, $f ];
                  }
                  }

                  if (@cross_product) {
                  say "$_->[0], // $_->[1]" for @cross_product[0..@cross_product-2];
                  say "$_->[0] // $_->[1]" for $cross_product[-1];
                  }


                  You can even avoid using up any memory as follows:



                  use Set::CrossProduct qw( );

                  my $i = Set::CrossProduct->new([ @names, @families ]);
                  my $N = $i->cardinality;
                  say sprintf '%1$s%3$s // %2$d', $i->get(), $_?',':'' for -$N+1..0;





                  share|improve this answer


























                    1












                    1








                    1






                    The alternative is to separate the output from the cross-product generation, and handling the last cast specially.



                    my @cross_product;
                    for my $n (0..$#names) {
                    for my $f (0..$#families) {
                    push @cross_product, [ $n, $f ];
                    }
                    }

                    if (@cross_product) {
                    say "$_->[0], // $_->[1]" for @cross_product[0..@cross_product-2];
                    say "$_->[0] // $_->[1]" for $cross_product[-1];
                    }


                    You can even avoid using up any memory as follows:



                    use Set::CrossProduct qw( );

                    my $i = Set::CrossProduct->new([ @names, @families ]);
                    my $N = $i->cardinality;
                    say sprintf '%1$s%3$s // %2$d', $i->get(), $_?',':'' for -$N+1..0;





                    share|improve this answer














                    The alternative is to separate the output from the cross-product generation, and handling the last cast specially.



                    my @cross_product;
                    for my $n (0..$#names) {
                    for my $f (0..$#families) {
                    push @cross_product, [ $n, $f ];
                    }
                    }

                    if (@cross_product) {
                    say "$_->[0], // $_->[1]" for @cross_product[0..@cross_product-2];
                    say "$_->[0] // $_->[1]" for $cross_product[-1];
                    }


                    You can even avoid using up any memory as follows:



                    use Set::CrossProduct qw( );

                    my $i = Set::CrossProduct->new([ @names, @families ]);
                    my $N = $i->cardinality;
                    say sprintf '%1$s%3$s // %2$d', $i->get(), $_?',':'' for -$N+1..0;






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 13 '18 at 13:39

























                    answered Nov 13 '18 at 13:32









                    ikegamiikegami

                    262k11176396




                    262k11176396























                        1














                        I thought of a variation to ikegami's (storing the results in a temporary array). There would be too many changes to comfortably fit in a comment, so here:



                        You could store the comma to the temporary list, too, and then remove it from only the last line.



                        #!/usr/bin/perl
                        use strict;
                        use warnings;

                        my @names = qw(ALLIES BOBBY CAKRA);
                        my @families = qw(A B C);
                        my @output_lines;

                        foreach my $name (@names) {
                        foreach my $family (@families) {
                        push @output_lines, [$name, ',', ' // ' . $family . "n"];
                        }
                        }

                        if (@output_lines) {
                        $output_lines[-1][1] = ''; # remove comma from last line
                        print map { @$_ } @output_lines;
                        }





                        share|improve this answer


























                          1














                          I thought of a variation to ikegami's (storing the results in a temporary array). There would be too many changes to comfortably fit in a comment, so here:



                          You could store the comma to the temporary list, too, and then remove it from only the last line.



                          #!/usr/bin/perl
                          use strict;
                          use warnings;

                          my @names = qw(ALLIES BOBBY CAKRA);
                          my @families = qw(A B C);
                          my @output_lines;

                          foreach my $name (@names) {
                          foreach my $family (@families) {
                          push @output_lines, [$name, ',', ' // ' . $family . "n"];
                          }
                          }

                          if (@output_lines) {
                          $output_lines[-1][1] = ''; # remove comma from last line
                          print map { @$_ } @output_lines;
                          }





                          share|improve this answer
























                            1












                            1








                            1






                            I thought of a variation to ikegami's (storing the results in a temporary array). There would be too many changes to comfortably fit in a comment, so here:



                            You could store the comma to the temporary list, too, and then remove it from only the last line.



                            #!/usr/bin/perl
                            use strict;
                            use warnings;

                            my @names = qw(ALLIES BOBBY CAKRA);
                            my @families = qw(A B C);
                            my @output_lines;

                            foreach my $name (@names) {
                            foreach my $family (@families) {
                            push @output_lines, [$name, ',', ' // ' . $family . "n"];
                            }
                            }

                            if (@output_lines) {
                            $output_lines[-1][1] = ''; # remove comma from last line
                            print map { @$_ } @output_lines;
                            }





                            share|improve this answer












                            I thought of a variation to ikegami's (storing the results in a temporary array). There would be too many changes to comfortably fit in a comment, so here:



                            You could store the comma to the temporary list, too, and then remove it from only the last line.



                            #!/usr/bin/perl
                            use strict;
                            use warnings;

                            my @names = qw(ALLIES BOBBY CAKRA);
                            my @families = qw(A B C);
                            my @output_lines;

                            foreach my $name (@names) {
                            foreach my $family (@families) {
                            push @output_lines, [$name, ',', ' // ' . $family . "n"];
                            }
                            }

                            if (@output_lines) {
                            $output_lines[-1][1] = ''; # remove comma from last line
                            print map { @$_ } @output_lines;
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 13 '18 at 20:33









                            SilvarSilvar

                            52326




                            52326






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53273095%2fhow-to-print-comma-in-the-middle-of-sentenced-when-necessary-part-1-perl%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Xamarin.form Move up view when keyboard appear

                                Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                Anylogic : not able to use stopDelay()