in reply to rectangularizing input to become array

Note also, as an alternative to substr, that pack with the A template will either truncate or pad to the right with spaces.

johngg@shiraz:~/perl/Monks$ perl -Mstrict -Mwarnings -MData::Dumper -e + ' open my $inFH, q{<}, \ <<__EOD__ or die $!; abcdef abcdefg abcde bcdefgh bcd __EOD__ chomp( my @lines = <$inFH> ); close $inFH or die $!; my $width = 6; my $height = 4; my $raRect = makeRect( \ @lines, $width, $height ); print Data::Dumper->Dumpxs( [ $raRect ], [ qw{ raRect } ] ); sub makeRect { my( $raLines, $width, $height ) = @_; my @rect; push @rect, pack qq{A$width}, shift @{ $raLines } for 1 .. $height +; return \ @rect; }' $raRect = [ 'abcdef', 'abcdef', 'abcde ', ' bcdef' ];

I hope this is of interest.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: rectangularizing input to become array
by Aldebaran (Curate) on Feb 28, 2019 at 23:45 UTC
    pack with the A template

    The many and various uses of pack. I'm glad to have another useful example. What's the A template?

    Code replication between readmore tags, invocation, output, then source.

    Can you say a few words about this line of code (I've never seen this before in Data::Dumper)?

    print Data::Dumper->Dumpxs( [ $raRect ], [ qw{ raRect } ] );

    Thanks.

      Unlike Dumper(), Data::Dumper->Dump() and ->Dumpxs() are not exported by Data::Dumper. However, for a little extra effort they do provide clearer output, especially if examining multiple data structures. They allow you to distinguish arrays and references to arrays, ditto for hashes. Many Monks recommend and use the more modern and flexible Data::Dump module but Data::Dumper has the advantage of being in core from way back so is useful if maintaining elderly servers in a closed environment running, say, Perl 5.8 or even earlier. Here is a simple example.

      I hope this is helpful.

      Cheers,

      JohnGG

      What's the A template?

      As documented in pack, it's a "text (ASCII) string, will be space padded." I showed the differences between some of those pack templates here.

      Can you say a few words about this line of code (I've never seen this before in Data::Dumper)? print Data::Dumper->Dumpxs( [ $raRect ], [ qw{ raRect } ] );

      Simplifying a lot, Dumpxs is just another name for Dump. (See Where is Data::Dumper->Dumpx?)