in reply to Re: A more efficient way to do this?
in thread A more efficient way to do this?

Not in Perl, but in Perl you could:

foreach my $field (@ldapFields) { $field =~ s/unvLocalPhone/Phone/; $field =~ s/unvLocalAddress/Address/; #... }

although that is probably less efficient in terms of execution time and only marginally better in terms of maintainability and programmer time. Besides, it doesn't do what the OP's code does - consider what happens if an element of @ldapFields were 'unvLocalPhoneNumber' for example.


True laziness is hard work

Replies are listed 'Best First'.
Re^3: A more efficient way to do this?
by mirage4d (Novice) on Feb 11, 2010 at 21:20 UTC
    All, Thanks for the responses. Yeah, the idea of using a hash had crossed my mind. I'm not very proficient with them, but it did occur to me that it might be the way to go in this situation. However, I should have mentioned in the original post that there will cases where fields will be mapped to the same new field name, i.e.:
    if ($field eq unvLocalPhone) || ($field eq unvCampusPhone)){ $field = "Phone"; }

    There will several or more cases of this actually. I am wondering if these instances make using a hash a bit more cumbersome?

    Performance is an issue with this script; it is already a bit slow due to the size of the directory being searched. I have read on more than one occasion that hashes, while good coding practice in Perl, are somewhat more resource intensive than simple arrays. Though in this case all of these conditionals may negate any theoretical performance gain achieved by using a simple array. Any thoughts here?

    Thanks again.
      Because hashes support a many-to-one style mapping, this should not be problematic, excepting of course the risk of one-offs in entering the hash values. You could easily just do something like:

      my %field_hash = (unvLocalPhone => "Phone", unvCampusPhone=> "Phone", unvLocalAddress => "Address", ); foreach my $field (@ldapFields) { if (exists $field_hash{$field}) { $field = $field_hash{$field}; } }

      As for performance, using a hash will be dramatically faster for this section than a series of elsifs would be - think of it as the hash takes a little longer to get the right answer the first time as opposed to possibly having to test every possible value. People much smarter than me have worked hard on making Perl's hash lookups quite fast.

      But more importantly, never forget Donald_Knuth's classic quote on the matter: premature optimization is the root of all evil. Wait until you have your code working, then benchmark and profile to find your bottlenecks. When you get that far, look up Devel::NYTProf and Benchmark.