From dd46eb28ae277cf82dd1c035cef66dd28a8b69eb Mon Sep 17 00:00:00 2001 From: Steve Hancock Date: Sat, 22 Jul 2023 17:01:27 -0700 Subject: [PATCH] add ability to write to SCALAR and ARRAY refs this is needed for a future update --- lib/Perl/Tidy/FileWriter.pm | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/lib/Perl/Tidy/FileWriter.pm b/lib/Perl/Tidy/FileWriter.pm index f1879d07..7c462276 100644 --- a/lib/Perl/Tidy/FileWriter.pm +++ b/lib/Perl/Tidy/FileWriter.pm @@ -49,7 +49,7 @@ BEGIN { # Do not combine with other BEGIN blocks (c101). my $i = 0; use constant { - _line_sink_object_ => $i++, + _write_line_ => $i++, _logger_object_ => $i++, _rOpts_ => $i++, _output_line_number_ => $i++, @@ -127,7 +127,6 @@ sub new { my ( $class, $line_sink_object, $rOpts, $logger_object ) = @_; my $self = []; - $self->[_line_sink_object_] = $line_sink_object; $self->[_logger_object_] = $logger_object; $self->[_rOpts_] = $rOpts; $self->[_output_line_number_] = 1; @@ -149,6 +148,30 @@ sub new { $self->[_K_last_arrival_] = -1; $self->[_save_logfile_] = defined($logger_object); + # parameter '$line_sink_object' tells where to store the line, as follows: + my $ref = ref($line_sink_object); + if ( !$ref ) { + Fault("FileWriter expects line_sink_object to be a ref\n"); + } + elsif ( $ref eq 'SCALAR' ) { + $self->[_write_line_] = sub { ${$line_sink_object} .= $_[0] }; + } + elsif ( $ref eq 'ARRAY' ) { + $self->[_write_line_] = sub { push @{$line_sink_object}, $_[0] }; + } + elsif ( $ref->can('write_line') ) { + $self->[_write_line_] = sub { $line_sink_object->write_line( $_[0] ) }; + } + else { + my $str = $ref; + if ( length($str) > 63 ) { $str = substr( $str, 0, 60 ) . '...' } + Fault(<[_line_sink_object_]->write_line("\n"); + $self->[_write_line_]->("\n"); $self->[_output_line_number_]++; $self->[_consecutive_blank_lines_]++; @@ -285,7 +308,7 @@ sub write_code_line { $self->[_consecutive_new_blank_lines_] = 0; $self->[_consecutive_nonblank_lines_]++; - $self->[_line_sink_object_]->write_line($str); + $self->[_write_line_]->($str); if ( chomp $str ) { $self->[_output_line_number_]++; } if ( $self->[_save_logfile_] ) { $self->check_line_lengths($str) } @@ -349,7 +372,7 @@ sub write_line { # Write a line directly to the output, without any counting of blank or # non-blank lines. - $self->[_line_sink_object_]->write_line($str); + $self->[_write_line_]->($str); if ( chomp $str ) { $self->[_output_line_number_]++; } if ( $self->[_save_logfile_] ) { $self->check_line_lengths($str) } -- 2.39.5