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
On Fri, 10 Sep 2004 11:58:30 -0500, Errin Larsen <[EMAIL PROTECTED]> wrote:
> On Fri, 10 Sep 2004 12:44:51 -0400, David Greenberg
> <[EMAIL PROTECTED]> wrote:
> > >foreach( @ARGV ) {
> > > open IN, $_ or die "Couldn't open $_: $!\n";
> > > chomp( my @data = <IN> );
> > > close IN;
> > > foreach( @data ) { s/\s+//g; }
> > > foreach( 0..$#data ) { $results[$_] .= $data[$_]; }
> > >}
> > This is a little shorter and saves on iterations:
> > for 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;
> > }
> >
> > -David
> >
>
> Can you throw the 'chomp' in the assignment in that 'map' statement?
> Then, can you also throw in the substitution in the mix? like this:
> @results = map{ my $line = chomp( s/\s+//g ); } ( <IN> );
>
> And if so, why not this:
>
> @results = map{ chomp( s/\s+//g ) } ( <IN> );
>
> As long as we're playing Perl-Golf!!
>
> I truly don't understand what 'map' is doing. Can you explain it to
> me? I have tried to read perldoc -f map but it's a little weird and
> hard to follow!
>
> --Errin
>
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>