简体   繁体   English

利用DBI模块将Perl代码与MySQLdb转换为python

[英]Translating a perl code, utilising the DBI module, to python with MySQLdb

I have little python experience, and I have zero perl knowledge, but I need to translate a perl code that connects to a MySQL server into python. 我几乎没有python经验,并且对perl的知识为零,但是我需要将连接到MySQL服务器的perl代码转换为python。

In the perl subroutine, after the standard connectivity actions, the code that appears is: 在perl子例程中,执行标准连接操作后,出现的代码为:

my @tmp = @{$dbh->selectall_arrayref( $sql )};

my @types;
foreach my $t (@tmp) {
push @types, @$t[0];
}

return @types;

where $sql is the MySQL selection query. 其中$ sql是MySQL选择查询。 What I would do in a python function is: 我在python函数中要做的是:

cursor = conn.cursor()
cursor.execute( sql )
tmp = cursor.fetchall()
types = list( len( tmp ) )
for item in tmp :
    types.append( item[0] )

return types

My question is what does @$t[0] contain and is that equivalent to the item[0] in tmp? 我的问题是@ $ t [0]包含什么,是否等同于tmp中的item [0]?

Thanks! 谢谢!

You should be able to run the code to discover equivalency, but yes those two things are equivalent. 您应该能够运行代码来发现等效性,但是是的,这两件事是等效的。

The thing that causes the syntax to be odd in the perl example is that perl had a very strict separation of scalars, arrays, and hashes in its early days and arrays and hashes could only have scalars as their stored values. 在perl示例中导致语法奇怪的是,perl在早期就对标量,数组和哈希进行了非常严格的分离,而数组和哈希只能将标量作为其存储值。 This was quickly improved by adding references into perl which are scalars that point to arrays and hashes, but the syntax was already set with that separation so additional operations had to be added to the language. 通过在perl中添加引用(它们是指向数组和哈希的标量),可以很快改善这一点,但是语法已经设置了这种分隔,因此必须在语言中添加其他操作。

As a result, the first line is taking a reference to an array of array references and dereferencing the outer reference so that it is now an array of array references. 结果,第一行正在对数组引用的数组进行引用,并取消对外部引用的引用,因此它现在是数组引用的数组。 It then loops over all those references inside it, dereferences them and takes the first element in the array. 然后,它遍历其中的所有那些引用,对它们取消引用,并获取数组中的第一个元素。 Because @$t[0] looks odd usually you would see it written as $t->[0] which doesn't require you to know that the array dereference operator ( @ ) binds tighter than the element access operator ( [0] ). 因为@$t[0]通常看起来很奇怪,所以您会看到它写为$t->[0] ,这不需要您知道数组取消引用运算符( @ )的绑定比元素访问运算符( [0] )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM