On Fri, 10 Sep 2004 13:17:40 -0400, David Greenberg
<[EMAIL PROTECTED]> wrote:
> I'm no expert, but chomp won't give you what you think it will:
> my @arr = ('a', "b\n", "c\n");
> print join (",",chomp (@arr));
> 
> This will print:
> 2
> 
> while this:
> my @arr = ('a', "b\n", "c\n");
> chomp (@arr);
> print join (",",@arr);
> 
> will print:
> a,b,c
> 
> Map will run whatever is in the code block (between the {}'s) on every
> value in the list passed to it (between the ()'s).  The last statement
> in the code block is like a return value.  Map builds the results list
> out of all of the return values.  With a foreach loop, it would be:
> my @results = ();
> foreach (<IN>) {
>      my $line = $_;
>      chomp $line;
>      $line =~ s/\s+//g;
>      push (@results, $line); #appends $line to the @results list
> }
> 
> Hope this helps.
> 
> -David
> 
> 

Thanks, David, for the 'map' explanation.  However, I've been playing
with this code, and, after your suggestion (above) it seems to be
broken.  Originally, the question was, taking atleast 2 seperate text
files on the command line, smoosh them together like this:

# ./smoosher file1 file2
OneFirst
TwoSecond
ThreeThird

if our text files are:
file1:
One
Two
Three

file2:
First
Second
Third

The code I have so far is (after your suggestion):

smoosher:
#!/usr/bin/perl

use warnings;
use strict;

unless( @ARGV >= 2 ) { die "Usage: $0 file1 file2 [file3...]\n"; }

my @results = ();

foreach my $file ( @ARGV ) {
        open IN, $file or die "Couldn't open $file: $!\n";
        @results = map { my $line = $_; chomp $line; $line =~
s/\s+//g; $line } (<IN>);
        close IN;
}       

foreach( @results ) { print "$_\n"; }

The first 'foreach' block in my original code, which was working, was:

foreach my $file ( @ARGV ) {
       open IN, $file or die "Couldn't open $file: $!\n";
       chomp( my @data = <IN> );
       close IN;
       foreach( @data ) { s/\s+//g; }
       foreach( 0..$#data ) { $results[$_] .= $data[$_]; }
}

So my question is, how can we use the map function, as you suggest, to
reduce the number of iterations, yet still keep our desired output? 
The key was the
  $results[$_] .= $data[$_];
line in there, which appended the current files line to the results
array, as opposed to replacing it, which is what our new code seems to
do.

--Errin

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to