[ABE.pm] rolling a loop

Ricardo SIGNES rjbs-perl-abe at lists.manxome.org
Tue Oct 19 10:59:37 CDT 2004


* Faber Fedor <faber at linuxnj.com> [2004-10-19T11:18:46]
>     @data = ("mytable1", "field1", "sum1", "col1",
> 	     "mytable2", "field2", "sum2", "col2",
> 	     "mytable3", "field3", "sum3", "col3",
>     );
> 
>     foreach my ($table, $field, $sum, $col) (@data) {
> 	$stmt = "update $table set $field = $sum where $col='Y'";
>         $dbh->do($stmt);
>     }
> 
> But that doesn't work in Perl. I think I spent too much time in Python.
> What's te proper Perl idiom/technique to roll this loop up?

How would Perl know which fields to break out at once?  In Python, you'd
probably have a list of lists, or tuple of tuples.  Otherwise, you can't
look at the datastructure alone and really know what's going on.

You could do this:
	@data = (
		[ 'mytable1', 'field1', 'sum1', 'col1' ],
		[ 'mytable2', ...

which I would write like this:
	@data = (
		[ qw(mytable1 field1 sum1 col1) ],
		[ qw(mytable2 ...

(perldoc perlop, quote-like operators)

Then:

	for (@data) {
		my ($table, $field, $sum, $col) = @$_;
		...
	}

Alternately, you could use a hashref, which is closer to what I'd really
do.

	my @data = (
		{ table => 't1', field => 'f1', sum => 's1', col => 'c1' }
		...

Then
	
	for (@data) {
		do_something("select $_->{field} FROM $_->{table}");
		...

-- 
rjbs
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.pm.org/archives/abe-pm/attachments/20041019/4f100210/attachment.bin


More information about the ABE-pm mailing list