in reply to Parse txt file into array of array

G'day Dr Manhattan,

You were almost there. You need to push an arrayref (not an array) of the split characters. Here's my test:

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @MainArray; while (<DATA>) { chomp; push @MainArray, [ split // ]; } print Dumper \@MainArray; __DATA__ Hello my name is Jack

Output:

$ pm_file_chars_to_AoA.pl $VAR1 = [ [ 'H', 'e', 'l', 'l', 'o' ], [ 'm', 'y' ], [ 'n', 'a', 'm', 'e' ], [ 'i', 's' ], [ 'J', 'a', 'c', 'k' ] ];

See also: perldsc - Perl Data Structures Cookbook

-- Ken

Replies are listed 'Best First'.
Re^2: Parse txt file into array of array
by Dr Manhattan (Beadle) on Jun 06, 2013 at 17:57 UTC

    Thanks that works great! Next question- How do I reference an element if I want to splice it?

    my $length = $#MainArray; for (my $x = 0; $x <= $length; $x++) + { my $smallLength = $MainArray[$#$x]; for(my $q = 0; $q <= $smallLength; $q++) { my $element = $MainArray[$x][$q]; if(some if statement concerning $element) { splice(How do I reference this part?); } } }

      I see hdb has shown the syntax you requested. Be aware that splice can be slow and there are often better alternatives. For instance, if you had intended to use splice to remove lowercase characters, you could have rewritten that entire block of code above as:

      for (@MainArray) { @$_ = grep { ! /[a-z]/ } @$_; }

      Here's my test:

      #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @MainArray; # Original array populating code while (<DATA>) { chomp; push @MainArray, [ split // ]; } # New alternative to 'splice' code for (@MainArray) { @$_ = grep { ! /[a-z]/ } @$_; } print Dumper \@MainArray; __DATA__ Hello my name is Jack

      Output:

      $ pm_file_chars_to_AoA_2.pl $VAR1 = [ [ 'H' ], [], [], [], [ 'J' ] ];

      -- Ken

        Ohke, so I now have this

        open (A1, "<An1.txt") or die "can't open"; open (A2, "<An2.txt") or die "can't open"; my @array1; my @array2; while (<A1>) { my $in = $_; chomp $in; push (@array1, [split(//, $in)]); } while (<A2>) { my $in = $_; chomp $in; push (@array2, [split(//, $in)]); } my $length = $#array1; my $total = 0; for (my $x = 0; $x <= $length; $x++) + { my $smallLength = scalar(@{$array1[$x]}); for(my $q = 0; $q <= $smallLength; $q++) { if($array1[$x][$q] =~ /^(\+|\_)$/ && $array2[$x][$q] =~ /^[A-Z +a-z]$/) { splice(@{$array2[$x]}, $q, 0, ''); } if($array2[$x][$q] =~ /^(\+|\_)$/ && $array1[$x][$q] =~ /^[A-Z +a-z]$/) { + splice(@{$array1[$x]}, $q, 0, ''); } $total++; } }

        I am trying to compare and calculate the diffence between to text files. Calculations come later in my code but that is not important. I get error message 'Use of uninitialized value in pattern match (m//)' for the 2 IF statements. Any idea why?