Perl. Format of row with number



  • There are lines.

    4455232
    8798798324893274
    74562846248376

    They must be seen:

    4 455 232
    8 798 798 324 893 274
    74 562 846 248 376

    i.e. at the end of the line every time 3 The symbol insert a gap.
    I can't make it.

    Not the most beautiful option:

    my $s = "23456779732984729374928748";
    my $m = length($s)%3 ? 3 - length($s)%3 : 0 ;
    my $ss = join(' ', ((' 'x$m . $s) =~ m/.../g));
    $ss =~ s/^\s+//g;
    print "$ss\n";
    

    Correct option (thank you. https://ru.stackoverflow.com/users/192530/andy-37 😞

    my $s = '1923456723456779732984729374928748';
    $s =~ s/(\d)(?=(\d{3})+$)/$1 /g;
    print "$s\n";
    


  • my $s = "12345678";
    my $m = length($s)%3 ? 3 - length($s)%3 : 0 ;
    my $ss = join(' ', ((' 'x$m . $s) =~ m/.../g));
    print "$ss\n";
    

    It works, but adds a gap at the beginning of 0, 1 or 2 (equalifying the length of the original line to 3N symbols). Leading gaps are easy to clean.

    P.S. No demons, no disc format)

    2nd method:

    http://www.perlmonks.org/?node_id=110137 ♪ Totally the same, only twice used reverseto separate three symbols from the end, not from the beginning. The most elegant way from there:

    my $s = '1234567';
    $s =~ s/(\d)(?=(\d{3})+$)/$1 /g;

    I think this way should be in the book.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2