On May 16, 2013, at 12:57 PM, Natxo Asenjo wrote: > hi, > > in a ldap script where I get a list of values of a multivalued attribute like > this: > > @memberof = qw( cn=group1,cn=xxx,dc=domain,dc=tld > cn=group2,cn=xxx,d=domain,dc=tld etc etc) ; > > I would like to use map to convert the list of elements to > @memberof = qw( group1 group2 group3 etc etc ) > > This is the code I have tried to capture the first string after the first '=' > in the $1 variable > > @memberof = map { s/^cn=(.*),.*$/$1/g; $_ } @memberof; > for ( @memberof ) { > print "[$_]" . " " ; > } > > but this snippet strangely cuts the start and the end of every array element > beginning and end so I get this: > > [group1,cn=xxx,dc=domain] [group2,cn=xxxx,dc=domain] > > so it is obviously not working. Is there a way to do this with map or do I > just have to process the array in a for loop and fill a new array with the > values? Just curious
The * in (.*) is "greedy", meaning the Perl regular expression engine will try to match as much as possible in each string after it finds the substring 'cn='. To make it "non-greedy", put a question mark after the quantifier: s/^cn=(.*?),/$1/ Note that the '.*$' characters ending your pattern are completely superfluous and will not affect the match or substitution in any way. Another way to achieve the same results is to match all non-comma characters up to the first comma: s/^cn=([^,]*),/$1/ Also note that since $_ inside the map block is an alias to the array members, you are modifying the array members in place, and you do not need to assign the result to the original array. Since using map in void context can be confusing, many Perl programmers would write it this way: s/^cn=([^,]*),/$1/ for @memberof; Since I wouldn't normally want to modify the original array, I might do it this way, taking advantage of the fact that the match operator (m//) in list context returns a list of the captured matches, so no substitution is required: my @newmemberof = map { m/^cn=([^,]*),/g } @memberof; -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/