in reply to Processing while reading in input

#!/usr/bin/perl # https://perlmonks.org/?node_id=1222680 use strict; use warnings; while( <DATA> ) { my ($cluster, $member) = split; print $cluster eq $member ? "\n" x ($. > 1) : ', ', $member; } print "\n"; __DATA__ Osat_a Osat_a # just one cluster member Atha_b Atha_b # >1 cluster member, this & next line = 2 members Atha_b Mtru_c Fves_d Fves_d # this & next 2 lines = 3 cluster members Fves_d Osat_e Fves_d Atha_f Atha_g Atha_g # just 1 cluster member Osat_h Osat_h Osat_h Atha_i Mtru_j Mtru_j # just 1 cluster member

Replies are listed 'Best First'.
Re^2: Processing while reading in input
by onlyIDleft (Scribe) on Sep 20, 2018 at 02:13 UTC

    Thank you, tybalt89. Your code worked in terms of generating the expected output.

    Could you please explain in detail the following 2 lines from your code? Thank you!

    my ($cluster, $member) = split; print $cluster eq $member ? "\n" x ($. > 1) : ', ', $member;

      Let me presume to answer for tybalt89.

      my ($cluster, $member) = split;

      This depends on default behavior of split, and is equivalent to
          my ($cluster, $member) = split ' ', $_;
      The  ' ' split pattern is a special case explained in split docs.

      print $cluster eq $member ? "\n" x ($. > 1) : ', ', $member;

      This is a bit more tricksy. From the inside out:

      • ($. > 1)  $. is input line counter (update: see perlvar).  ($. > 1) evaluates to either '' (empty string) or 1 and will be 1 for every input line after the first.
      • "\n" x ($. > 1) Repeats a newline zero times for the first line of input (empty string silently promoted to 0 in this special case), once for every subsequent input line.
      • $cluster eq $member ? Newline_or_Nada : ', ' Ternary expression. If  $cluster eq $member true, output newline for every input line after the first (see previous item); if false, output  ', ' string.
      • print Ternary_Expression, $member; print result of ternary expresssion (see previous item), then  $member string.
      And that's all there is to it (I think).

      Update: Minor wording changes.


      Give a man a fish:  <%-{-{-{-<