in reply to Re: using Path::Tiny and reformating result
in thread using Path::Tiny and reformating result

Thx haukex, that got rid of the warning. I'm not sure that I understand it completely, but I do understand the absence of a warning. I do have suitable output to frame the problem. It's 39 lines of text all told, so if seeing that much data is going to make the reader grumpy, then don't open the readmore tags. I'm hoping to get the pre tags right on this. (Order seems to matter on these tags.)

$ ./2.tiny.pl 
/home/bob/1.promises.txt
i is 0
                       Oбещания   

i is 1


i is 2
  Если эта фаза нашего развития болезненна для нас, мы

i is 3
будем удивлены, когда половина пути окажется позади. Мы

i is 4
познáем новую свободу и новое счастье. Мы не будем сожалеть

i is 5
о нашем прошлом и вместе с тем не захотим полностью

i is 6
забывать о нем. Мы узнаем, что такое чистота, ясность, покой.

i is 7
Как бы низко мы ни пали в прошлом, мы поймем, что наш опыт

i is 8
может быть полезен другим. Исчезнут ощущения ненужности и

i is 9
жалости к себе. Мы потеряем интерес к вещам, которые

i is 10
подогревают наше самолюбие, и в нас усилится интерес к

i is 11
другим людям. Мы освободимся от эгоизма. Изменится наше

i is 12
мировоззрение, исчезнут страх перед людьми и неуверенность

i is 13
в экономическом благополучии. Мы интуитивно будем знать, как

i is 14
вести себя в ситуациях, которые раньше нас озадачивали. Мы

i is 15
поймем, что Бог делает для нас то, что мы не смогли сами

i is 16
сделать для себя.

i is 17


i is 18
     Не слишком ли это звучит многообещающе? Нет. Все это

i is 19
произошло со многими из нас, с одними раньше, с другими

i is 20
позже. Все это становится явью, если приложить усилия.

i is 21


i is 22
                      Promises

i is 23


i is 24
       If we are painstaking about this phase of our development, we will be amazed

i is 25
     before half through! We are going to know a new freedom and happiness. We

i is 26
     will not regret the past nor wish to shut the door on it. We will comprehend the

i is 27
     word serenity and know peace. No matter how far down the scale we have

i is 28
     gone, we will see how our experience can benefit others. That feeling of use-

i is 29
     lessness and self-pity will disappear. We will lose interest in selfish things and

i is 30
     gain interest in our fellows. Self-seeking will slip away. Our whole attitude

i is 31
     and outlook upon life will change. Fear of people and of economic insecurity

i is 32
     will leave us. We will intuitively know how to handle situations which used to

i is 33
     baffle us. We will suddenly realize that God is doing for us what we could not

i is 34
     do for ourselves.

i is 35


i is 36
       Are these extravagant promises? We think not. They are being fulfilled among

i is 37
     us—sometimes quickly, sometimes slowly. They will always materialize if we

i is 38
     work for them.

New script:

#!/usr/bin/perl -w
use strict;
use 5.010;
use Path::Tiny;
use utf8;
use open qw/:std :utf8/;
 
# creating Path::Tiny objects
 
my $dir = path("/home/bob");
my $name = "1.promises.txt";
my $new_name = path($dir,"1.revised.txt");
 
my $path1 = path($dir, $name); # list
say $path1; 
#say "lines are @lines";
my @lines = $path1->lines_utf8;

foreach my $i (0 .. $#lines) 
{
 say "i is $i";
 say "$lines$i";
 $lines$i =~ s/God/an arbitrary higher power/;
 $lines$i=~ s/Бог/большая сила/;
}

$new_name->spew_utf8( @lines );

__END__ 

A couple problems solved, but I'm still fishing for how I format this into homogenous-looking paragraphs.

Update: attempting again to use pre tags successfully; using them in conjunction with code tags seems not to display wide characters properly

  • Comment on Re^2: using Path::Tiny and reformating result

Replies are listed 'Best First'.
Re^3: using Path::Tiny and reformating result
by haukex (Chancellor) on Jun 30, 2018 at 20:10 UTC
    attempting again to use pre tags successfully; using them in conjunction with code tags seems not to display wide characters properly

    Yes, the issue with <code> vs. <pre> tags and Unicode characters only working in the latter is a known issue on PerlMonks.

    I'm still fishing for how I format this into homogenous-looking paragraphs.

    Have a look at the core module Text::Wrap. Here's one way, I'm using the "paragraph mode" supported by $/ to read the file:

    use warnings; use strict; use open qw/:std :utf8/; use Text::Wrap 'wrap'; open my $fh, '<:raw:encoding(UTF-8)', '1.promises.txt' or die $!; local $/ = ''; local $Text::Wrap::columns = 71; while (<$fh>) { s/^\s+|\s+$//mg; if (/\A\w+\z/) { print ' ' x int( (71-length)/2 ), $_, "\n"; next; } s/\n|\s{2,}/ /g; print wrap(' 'x5, '', $_), "\n"; } close $fh;

    Output:

                                   Oбещания
         Если эта фаза нашего развития болезненна для нас, мы будем
    удивлены, когда половина пути окажется позади. Мы познáем новую
    свободу и новое счастье. Мы не будем сожалеть о нашем прошлом и вместе
    с тем не захотим полностью забывать о нем. Мы узнаем, что такое
    чистота, ясность, покой. Как бы низко мы ни пали в прошлом, мы поймем,
    что наш опыт может быть полезен другим. Исчезнут ощущения ненужности и
    жалости к себе. Мы потеряем интерес к вещам, которые подогревают наше
    самолюбие, и в нас усилится интерес к другим людям. Мы освободимся от
    эгоизма. Изменится наше мировоззрение, исчезнут страх перед людьми и
    неуверенность в экономическом благополучии. Мы интуитивно будем знать,
    как вести себя в ситуациях, которые раньше нас озадачивали. Мы поймем,
    что Бог делает для нас то, что мы не смогли сами сделать для себя.
         Не слишком ли это звучит многообещающе? Нет. Все это произошло со
    многими из нас, с одними раньше, с другими позже. Все это становится
    явью, если приложить усилия.
                                   Promises
         If we are painstaking about this phase of our development, we
    will be amazed before half through! We are going to know a new freedom
    and happiness. We will not regret the past nor wish to shut the door
    on it. We will comprehend the word serenity and know peace. No matter
    how far down the scale we have gone, we will see how our experience
    can benefit others. That feeling of use- lessness and self-pity will
    disappear. We will lose interest in selfish things and gain interest
    in our fellows. Self-seeking will slip away. Our whole attitude and
    outlook upon life will change. Fear of people and of economic
    insecurity will leave us. We will intuitively know how to handle
    situations which used to baffle us. We will suddenly realize that God
    is doing for us what we could not do for ourselves.
         Are these extravagant promises? We think not. They are being
    fulfilled among us—sometimes quickly, sometimes slowly. They will
    always materialize if we work for them.
    

      Thx, haukex, I was gonna spend a month on that, and I only had a few days before it needs to be done. I was almost through the logic of centering, but yours looks so much cleaner. This is essentially your same program but using Path::Class to specify input and output files and adding a couple customizations for this particular text:

      #!/usr/bin/perl -w
      use strict;
      use 5.010;
      use Path::Tiny;
      use utf8;
      use open qw/:std :utf8/;
      use Text::Wrap 'wrap';
      
      my $dir      = path("/home/bob");
      my $name     = "1.promises.txt";
      my $new_name = path( $dir, "7.revised.txt" );
      my $path1    = path( $dir, $name );
      say $path1;
      say "new name is $new_name";
      open my $gh, '>:raw:encoding(UTF-8)', "$new_name" or die $!;
      open my $fh, '<:raw:encoding(UTF-8)', "$path1"    or die $!;
      local $/                   = '';
      local $Text::Wrap::columns = 71;
      
      while (<$fh>) {
         say "default is $_";
         s/God/a higher power/;
         s/Бог/Высшая Сила/;
         s/^\s+|\s+$//mg;
         if (/\A\w+\z/) {
            print $gh "\n";
            print $gh ' ' x int( ( 71 - length ) / 2 ), $_, "\n";
            print $gh "\n";
            next;
         }
         s/\n|\s{2,}|\t/ /g; 
         print $gh wrap( ' ' x 5, '', $_ ), "\n";
      }
      close $fh;
      close $gh;
      system("gedit $new_name &");
      system("cat $new_name &");
      __END__ 

      I'm still not completely clear what local $/ = ''; does, even with the say statements for $_. It's exactly what I need, but perlvar does not discuss what it means to set it like this, which seems, as you say, to be paragraph mode. (?)

        ... I'm still not completely clear what local $/ = ''; does ... perlvar does not discuss what it means to set it like this ...

        Quoth perlvar:

        IO::Handle->input_record_separator(EXPR)
        $INPUT_RECORD_SEPARATOR
        $RS
        $/
        The input record separator, newline by default. This influences Perl's idea of what a "line" is. ... [Treats] empty lines as a terminator if set to the null string. ... Setting it to "\n\n" means something slightly different than setting to "", if the file contains consecutive empty lines. Setting to "" will treat two or more consecutive empty lines as a single empty line. Setting to "\n\n" will blindly assume that the next input character belongs to the next paragraph, even if it's a newline. ...
        So yes,  local $/ = ''; sets what you might call "indulgent" (update: or maybe "greedy"?) paragraph mode.
        c:\@Work\Perl\monks\Magnolia25>perl -wMstrict -le "my $data = qq{line 1 \n} . qq{line 2 \n} . qq{\n} . qq{\n} . qq{\n} . qq{\n} . qq{\n} . qq{line 8 \n} . qq{line 9 \n} . qq{\n} . qq{\n} . qq{\n} . qq{\n} . qq{line 14 \n} . qq{\n} . qq{\n} . qq{\n} ; print qq{[[$data]] \n}; ;; open my $dfh, '<', \$data or die $!; ;; local $/ = ''; while (<$dfh>) { print qq{block <<$_>>}; } " [[line 1 line 2 line 8 line 9 line 14 ]] block <<line 1 line 2 >> block <<line 8 line 9 >> block <<line 14 >>
        Try assigning  "\n\n" to  $/ as an experiment; how many blocks get printed out then?


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