in reply to Using map

Ok, for one...
$_ =~ s/taxman.add.subloc.//g if $_ =~ /taxman.add.subloc./
is rather a waste of time...
s/taxman\.add\.subloc\.//g
is sufficient since s will only do the replace if it matches, making the check for a match just slow you down... also you will notice that I removed $_ =~... s/// and // default to use $_, so it is just extra typing (you can do it if you want). I also changed your . to \. this is because . has special meaning in a regexp, which is that . will match any single character...

As to why you are editing your main array. Map goes through your array and aliases each item of the array to $_. That means that any changes to $_ change the array items (this happens in for(@session_keys) as well), what you want to do is find the value you need and return it from the code block without editing $_... like so

my @sub_locs = map { /taxman\.add\.subloc\.(.*)/ ? $1 : () } @session_ +keys;
That should do what you want... the .* matches everything after taxman.add.subloc. and the parens around it tell perl to store what it finds in $1. the ? : says if I matched sucessfully, return $1, if not return () which means nothing will be put into @sub_locs unless there is a match...

sound good?

Update my using return was wrong.. fixed...

                - Ant
                - Some of my best work - Fish Dinner

Replies are listed 'Best First'.
Re: Re: Using map
by blackjudas (Pilgrim) on Oct 05, 2001 at 10:16 UTC
    My apologies for posting bad code, the result you see above was a feeble attempt to see where I was going wrong because I was not receiving the results I was expecting. I apologise for this, my original code read:
    my @sub_locs = map { s/taxman.add.subloc.// } @session_keys;

    While I read up on most of the posts, the perldocs and looked at the examples in the camel book, the concept must have missed me by a mile. Thanks for clarifying, I am aware of the dots though for some reason I didn't escape them, I guess I got lazy since I used to escape them in previous code I've written, though I haven't experienced any funky results by not escaping them yet.

    BlackJudas
      You would only receive funky results if you had a file that had a character where you are looking for a . that was not a . say if you had a file name taxman.add2subloc.foo you would still match even though it has a 2 instead of a .
      And let me tell you... you don't not want to try to track that error down :) Those are the impossible to find errors :)

      and, as has been said, $_ inside the map code block is an alias to the item in the array, so any changes made directly to it (like substitutions) will edit the values in the array.

                      - Ant
                      - Some of my best work - Fish Dinner