in reply to Help with loops

@email = ($email,$pscemail1,$pscemail2,$pscemail3,$pscemail4,$pscemail5,$pscemail6,$pscemail7,$pscemail8);

You already have a solution thanks to brother Discipulus so here's just an additional handy hint. Every time you find yourself appending a digit to the name of a scalar variable ask yourself the question, "Should I be using an array here instead?".

The answer is almost invariably, "Yes!".

We haven't seen your code which sets values (or not) for $pscemail1, $pscemail2, etc. but why not try just using a single @pscemail array instead and see how much neater it might make your code? HTH.


"It doesn't work" is as useful to a developer as "I'm ill" is to a medic. Be specific.

Replies are listed 'Best First'.
Re^2: Help with loops
by htmanning (Friar) on May 06, 2016 at 04:47 UTC
    Thanks for this. I thought I was using an array. The pscemails are set in the database. It's rare to have 8 emails, but I retrieve them by searching the database. If they are there I retrieve them with these lines:
    $pscemail1 = $pointer->{'pscemail1'}; $pscemail2 = $pointer->{'pscemail2'}; $pscemail3 = $pointer->{'pscemail3'}; $pscemail4 = $pointer->{'pscemail4'}; $pscemail5 = $pointer->{'pscemail5'}; $pscemail6 = $pointer->{'pscemail6'}; $pscemail7 = $pointer->{'pscemail7'}; $pscemail8 = $pointer->{'pscemail8'};
    Then I put all of them into the list and send the email:
    @email = ($email,$pscemail1,$pscemail2,$pscemail3,$pscemail4,$pscemail +5,$pscemail6,$pscemail7,$pscemail8); foreach $toemail (@email) { Send the email }
    Is there a better way to do it?

      Better, just be direct  @email = (  $pointer->{'pscemail1'},  $pointer->{'pscemail2'} ... );

      But thats too repetitive , too many quotes/arrows/$pointer , too much typing and/or copy/paste, so shorter  @email = @{$pointer}{ qw/ pscemail1 pscemail2 ... /});

      Thats much less repetitive and shorter, but still too repetitive, so shorter to write  @emails = map { $pointer->{'pscemail'.$_} } 1 .. 8;

      Another alternative, just to blow your mind, a tiny bit of api as language, if $pointer was more than a simple hash, if it was an object like a $row, with an emails method,

      you could use  for my $toemail ( $row->emails ){ ... }

      yeah you could eliminate @emails and just drop that map statement instead of $row->emails.... choices sure complicate stuff :D