in reply to Re: Concatenation to elements in an array !
in thread Concatenation to elements in an array !

This node falls below the community's threshold of quality. You may see it by logging in.
  • Comment on Re^2: Concatenation to elements in an array !

Replies are listed 'Best First'.
Re^3: Concatenation to elements in an array !
by chromatic (Archbishop) on Mar 24, 2011 at 20:25 UTC
    I am looking for a function which can be applied to every element of the string without spanning the whole array using map or any other loops.

    Why? Any reasonable (non-golf) solution to this problem would use map or a loop. If you're a Scheme programmer, you could also use recursion, but you asked for a Perl solution and you have the reasonable Perl solution.

Re^3: Concatenation to elements in an array !
by GrandFather (Saint) on Mar 24, 2011 at 21:06 UTC

    You can take one of two approaches:

    1/ edit the string, probably using a regex

    2/ split the string into an array and edit the elements

    We can't tell you what will work best because you don't tell us enough about the overall process. You asked in essence "how do I edit elements of an array" and got good answers. Now you show us a process involving reading a line, spliting it into an array, editing the array, ... . Then you tell us you don't want to do that but instead want to do something else! What do you want to do?

    I suggest you try several approaches on a small subset of your data and benchmark them to see what works best. The following may be a good starting point:

    use strict; use warnings; use Benchmark qw(cmpthese); my $line = join (',', 1 .. 1000) . "\n"; my $data = $line x 100; cmpthese ( -1, { array => \&asArray, str => \&asStr, } ); sub asArray { my $outStr; open my $in, '<', \$data; open my $out, '>', \$outStr; print $out join ',', map {s/$/a/; $_} split ',' while <$in>; return $outStr; } sub asStr { my $outStr; open my $in, '<', \$data; open my $out, '>', \$outStr; while (<$in>) { s/(?=,)|\n/a/g if /\S/; print $out $_; } return $outStr; }

    Prints:

    Rate array str array 6.23/s -- -28% str 8.61/s 38% --

    which indicates that the differences between the two techniques are small enough that they would probably be completely lost in the I/O time.

    True laziness is hard work
Re^3: Concatenation to elements in an array !
by ikegami (Patriarch) on Mar 24, 2011 at 20:52 UTC

    You can't do something repeatedly without some loop.

    That doesn't mean that all loops are equal, though. You might be able to use something like

    $line =~ s/(?:\t|\z)\K/a/g; # Requires 5.10+ $line =~ s/(\t|\z)/${1}a/g; # Slower, but works with earlier versions

    Update: Accidentally said "with some loop." Fixed.