Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Updating variable in a loop

by htmanning (Friar)
on Jun 07, 2016 at 21:45 UTC ( [id://1165113]=perlquestion: print w/replies, xml ) Need Help??

htmanning has asked for the wisdom of the Perl Monks concerning the following question:

Monks, I'm searching a database to find certain record. If the record matches my terms, I send an email to that user. I'm using a loop to go through all of the records. I would like to update a single variable that I will later use to log every record that was sent an email. How can I update that variable within the loop? When I run the script from the command line, I have a print line like this, that also updates the count. I stuff the count into a log after the loop is finished:
print "email sent to: $contact <$toemail><br>\n"; $count++
I'd like to also do something like:
$log = email sent to: $contact <$toemail><br>";
But it needs to be updated with all the emails sent, so I can make a single log entry, via separate routine, once the loop is finished. Make sense?

Replies are listed 'Best First'.
Re: Updating variable in a loop
by Paladin (Vicar) on Jun 07, 2016 at 21:54 UTC
    You can use something like the following to construct one large string:
    my $log = ""; for my $item (@stuff) { do_something($item); $log .= "Email sent to: $item<br>\n"; } print $log_file $log;
    The  $log .= "..." appends the string to $log each time through the loop so at the end, it's one large string.
Re: Updating variable in a loop
by stevieb (Canon) on Jun 07, 2016 at 21:58 UTC

    If I understand you correctly, here's an untested example that should provide guidance:

    my $count = 0; my @sent; while (get_entry_from_db()){ if (/match/){ ...; # send email and do other stuff $count++; push @sent, [$contact, $email]; } } print "users mailed: $count\n"; for my $entry (@sent){ my ($contact, $email) = @$entry; print "email sent to: $contact <$email><br>"; }

    I've used an array of arrays here, instead of just appending the full string to the array, but you can go that route as well.

    update: changed default var to named in for() loop for clarity

      So I would use another loop within my loop? Here's what I'm doing:
      $SQL = "Select * from database where (TO_DAYS(enddate) - TO_DAYS(Now() +) = 8) AND payment!='premium'"; &Do_SQL; $recordcount = $sth->rows; if ($recordcount > 0) { $sendEmails = 'yes'; } if ($sendEmails eq 'yes') { $count = 0; while ($pointer = $sth->fetchrow_hashref) { $contact = $pointer->{'contact'}; $toemail = $pointer->{'email'}; open (MAILPROG....."; SEND THE EMAIL HERE.... close (MAIL); print "email sent to: $contact <$toemail>\n"; $count++ } print "Sent $count emails.\n"; $action = "Email Reminders sent!"; $log = "Sent $count emails."; &log_it;
      I'd like $log to also have every email address that received an email. It would look something like this in the log:
      Sent 4 emails.<br> Email sent to user1<br> Email sent to user2<br> Email sent to user3<br> Email sent to user4<br>
      I need to get the $log variable within my existing loop but have it updated with every email. So do I have to run a separate loop within my loop?
Re: Updating variable in a loop
by FreeBeerReekingMonk (Deacon) on Jun 07, 2016 at 22:20 UTC
    #!/usr/bin/perl use DBI; my $dbfile = 'test.db'; # your database file my $need2create = ! -f $dbfile; my $dbh = DBI->connect( # connect to your database, create if + needed "dbi:SQLite:dbname=$dbfile", # DSN: dbi, driver, database file "sq", # no user "lite", # no password { RaiseError => 1 }, # complain if something goes wrong ) or die $DBI::errstr; my $table = 'test'; my @rows = qw(id hobby email); if($need2create){ print "Creating $dbfile -> $table \n"; $dbh->do("create table $table (".join(',',@rows).')') or die $DBI +::errstr; my @DATA = ('1|chess|camelot@aorta.com','2|math|dude@oops.no','3|m +ath|foo@bar.com'); for my $data (@DATA){ $str ="insert into '$table' ('".join("','",@rows)."')"." value +s ('".join("','",split(/\|/,$data))."')"; print $str ."\n"; $dbh->do($str) or die $DBI::errstr; } } $sql ="select * from $table"; my $sth = $dbh->prepare($sql); $sth->execute(); my @SENDTO; while (my @row = $sth->fetchrow_array) { # retrieve one row if($row[1]=~/math/i){ print "emailing $row[2]\n"; push(@SENDTO, $row[2]); # print "". join(", ", @row), "\n"; } } for my $who (@SENDTO){ $log = "I have emailed $who\n"; print $log; &log_it; }

    Prints:

    emailing dude@oops.no emailing foo@bar.com I have emailed dude@oops.no I have emailed foo@bar.com

    Alternative is that you concatenate your string with newlines, thus:

    my $SENDTO = ""; # start with empty string while (my @row = $sth->fetchrow_array) { # retrieve one row if($row[1]=~/math/i){ $SENDTO .= "emailing $row[2]\n"; push(@SENDTO, $row[2]); } } $log = $SENDTO; &log_it;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1165113]
Approved by sweetblood
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (7)
As of 2024-04-23 18:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found