perl 10和1哪个是truee 0否

[转载]比较perl+python
已有 10004 次阅读
|个人分类:|系统分类:|关键词:255 normal python|文章来源:转载
转自: &/itech/archive//2468917.html&from &http://hyperpolyglot.org/scripting------------------------------------------------------------------------------------------------比较perl+python&&
use&strict;
import&os, re, sys
\$ perl&-v
\$ python -V
\$ perl foo.pl
\$ python foo.py
\$ perl -de 0
\$ perl -e 'print("hi\n")'
\$ python -c "print('hi')"
\n (newline)
comment line
another line
use triple quote string literal:
'''comment line
another line'''
变量和操作符
(\$x, \$y, \$z) = (1, 2, 3);
discarded:
(\$x, \$y) = (1, 2, 3);
# \$z set to
(\$x, \$y, \$z) = (1, 2);
x,&y,&z&= 1, 2, 3
ValueError:
x,&y&= 1, 2, 3
ValueError:
x,&y,&z&= 1, 2
(\$x, \$y) = (\$y, \$x);
x,&y&= y, x
+= -= *=&none&/= %=&**=
&&=&||= ^=
&&= &&= &= |= ^=
# do not return values:
+= -= *= /=&//= %=&**=
&&= &&= &= |= ^=
my&\$x&= 1;
my&\$y&= ++\$x;
my&\$z&=&--\$y;
my&(@a,&%d);
my&\$x&= 1;
my&(\$y,&\$z) = (2, 3);
# in function body:
a,&d&= [], {}
y,&z&= 2, 3
our&(\$g1,&\$g2) = (7, 8);
sub&swap_globals&{
&&(\$g1, \$g2) = (\$g2, \$g1);
g1,&g2&= 7, 8
def&swap_globals():
&&global&g1, g2
&&g1, g2 = g2, g1
use&constant&PI&=& 3.14;
# uppercase identifiers
# constant by convention
!&defined&\$v
error under&&otherwise&undef
raises&NameError
True False
undef&0&0.0&"" "0"&()
False&None&0&0.0&''&[] {}
lower precedence:
and or xor not
and or not
\$x & 0 ? \$x : -\$x
x&if&x & 0&else&-x
numbers only:&== != & & &= &=
strings:&eq ne gt lt ge
comparison operators are chainable:
== != & & &= &=
73.9 +&".037"
7 +&int('12')
73.9 +&float('.037')
'value: '&+&str(8)
+ - * /&none&%&**
+ - * / // %&**
int&( 13 / 5 )
q, r =&divmod(13, 5)
float(13) / 5
# Python 3:
use&Math::Trig&qw(
&&tan asin acos atan);
sqrt exp log sin
cos&tan asin acos
atan&atan2
from&math&import&sqrt, exp, log, \
sin, cos, tan, asin, acos, atan, atan2
# cpan -i Number::Format
use&Number::Format&'round';
use&POSIX&qw(ceil floor);
round(\$x, 0)
floor(\$x)
import&math
int(round(x))
math.ceil(x)
math.floor(x)
use&List::Util&qw(min max);
min(1,2,3);
max(1,2,3);
@a&= (1,2,3);
min(1,2,3)
max(1,2,3)
min([1,2,3])
max([1,2,3])
raises&ZeroDivisionError
use&Math::BigInt&to
create arbitrary length integers
becomes arbitrary length integer of type long
raises&OverflowError
int(rand() * 100)
import&random
random.randint(0,99)
random.random()
random.gauss(0,1)
my&\$sd&=&srand;
srand(\$sd);
import&random
random.seed(17)
random.getstate()
random.setstate(sd)
&& && & | ^ ~
&& && & | ^ ~
字符串操作
"don't say \"no\""
'don\'t say
'don\'t say "no"'
"don't say
'''don't say
say "no\""""
triple quote literals only
double quoted:
\a \b \cx&\e \f \n \r \t
\xhh&\x{hhhh} \ooo&&&Perl 5.14:&\o{ooo}
single quoted:
single and double quoted:
\newline&\\ \' \"
\a \b \f \n \r \t \v \ooo&\xhh
\uhhhh&\Uhhhhhhhh
my&\$count&= 3;
my&\$item&=&"ball";
print&"\$count \${item}s\n";
item&=&'ball'
print(‘%s %s’ % (count, item))
my&\$fmt&=&"lorem %s %d %f";
sprintf(\$fmt,&"ipsum", 13, 3.7)
'lorem %s %d %f'&% ('ipsum', 13, 3.7)
fmt&=&'lorem {0} {1} {2}'
fmt.format('ipsum', 13, 3.7)
\$word =&"amet";
\$s =&&&EOF;
lorem ipsum
dolor sit \$word
字符串连接
my&\$s&=&"Hello, ";
my&\$s2&= \$s .&"World!";
s&=&'Hello, '
s2&= s +&'World!'
juxtaposition can
be used to concatenate literals:
s2&=&'Hello, ' "World!"
字符串复制
my&\$hbar&=&"-"&x&80;
hbar&=&'-'&* 80
字符串分隔
split(/\s+/,&"do re mi fa")
split(/\s+/,&"do re mi fa", 2)
split(/(\s+)/,&"do re mi fa");
split(//,&"abcd")
'do re mi fa'.split()
'do re mi fa'.split(None, 1)
re.split('(\s+)',&'do re mi fa')
list('abcd')
join(" ",&qw(do re mi fa))
' '.join(['do',&'re',&'mi',&'fa'])
uc("lorem")
lc("LOREM")
ucfirst("lorem")
'lorem'.upper()
'LOREM'.lower()
'lorem'.capitalize()
# cpan -i Text::Trim
use&Text::Trim;
trim&" lorem
rtrim&"lorem
' lorem '.strip()
' lorem'.lstrip()
'lorem '.rstrip()
sprintf("%-10s",&"lorem")
sprintf("%10s",&"lorem")
'lorem'.ljust(10)
'lorem'.rjust(10)
length("lorem")
len('lorem')
字符串index
index("lorem ipsum",&"ipsum")
rindex("do re re",&"re")
return&-1&if not
'do re re'.index('re')
'do re re'.rindex('re')
raise&ValueError&if
substr("lorem ipsum", 6, 5)
'lorem ipsum'[6:11]
访问字符串中字母
can't use index notation with strings:
substr("lorem ipsum", 6, 1)
'lorem ipsum'[6]
正则表达式
/lorem|ipsum/
qr(/etc/hosts)
re.compile('lorem|ipsum')
char class abbrevs:
. \d \D \h \H \s \S \v \V \w \W
anchors:&^ \$ \A \b \B
char class abbrevs:
. \d \D \s \S \w \W
anchors:&^ \$ \A \b \B
if&(\$s =~&/1999/) {
&&print&"party!\n";
if&re.search('1999', s):
&&print('party!')
"Lorem"&=~&/lorem/i
re.search('lorem',&'Lorem', re.I)
re.I re.M re.S re.X
my&\$s&=&"do re mi mi mi";
\$s =~&s/mi/ma/g;
s&=&'do re mi mi mi'
s&= re.compile('mi').sub('ma', s)
\$rx =&qr/(\d{4})-(\d{2})-(\d{2})/;
(\$yr, \$mo, \$dy) = (\$1, \$2, \$3);
rx&=&'(\d{4})-(\d{2})-(\d{2})'
re.search(rx,&'')
yr,&mo,&dy&= m.groups()
my&\$s&=&"dolor sit amet";
@a&= \$s =~&m/\w+/g;
s&=&'dolor sit amet'
a&= re.findall('\w+', s)
"do do"&=~&/(\w+) \1/
my&\$s&=&"do re";
\$s =~&s/(\w+) (\w+)/\$2 \$1/;
rx&= re.compile('(\w+) (\w+)')
rx.sub(r'\2 \1',&'do re')
日期时间类型
Time::Piece&if&use
Time::Piece&in effect, otherwise tm array
datetime.datetime
use&Time::Piece;
my&\$t&=&localtime(time);
my&\$utc&=&gmtime(time);
import&datetime
datetime.datetime.now()
datetime.datetime.utcnow()
use&Time::Local;
use&Time::Piece;
my&\$epoch&= timelocal(\$t);
my&\$t2&=&localtime();
from&datetime&import&datetime&as&dt
epoch&=&int(t.strftime("%s"))
t2&= dt.fromtimestamp()
\$epoch =&time;
import&datetime
datetime.datetime.now()
epoch&=&int(t.strftime("%s"))
use&Time::Piece;
\$t =&localtime(time);
\$fmt =&"%Y-%m-%d
%H:%M:%S";
print&\$t-&strftime(\$fmt);
t.strftime('%Y-%m-%d %H:%M:%S')
Tue Aug 23&19:35:19&2011
&19:35:59.411135
字符串转为时间
use&Time::Local;
use&Time::Piece;
\$s =&"&10:00:00";
\$fmt =&"%Y-%m-%d
%H:%M:%S";
\$t = Time::Piece-&strptime(\$s,\$fmt);
from&datetime&import&datetime
s&=&'&10:00:00'
fmt&=&'%Y-%m-%d %H:%M:%S'
datetime.strptime(s, fmt)
# cpan -i Date::Parse
use&Date::Parse;
\$epoch = str2time("July 7, 1999");
# pip install python-dateutil
import&dateutil.parser
s&=&'July 7, 1999'
dateutil.parser.parse(s)
Time::Seconds&object if&use
Time::Piece& not meaningful to subtract tm arrays
datetime.timedelta&object
use&Time::Seconds;
\$now =&localtime(time);
\$now += 10 * ONE_MINUTE() + 3;
import&datetime
datetime.timedelta(
&&minutes=10,
&&seconds=3)
datetime.datetime.now() + delta
Time::Piece&has local timezone if
created withlocaltime&and UTC timezone if created with&&tm
arrays have no timezone or offset info
a&datetime&object has no timezone
information unless a&tzinfo&object is provided when it is
# cpan -i DateTime
use&DateTime;
use&DateTime::TimeZone;
\$dt = DateTime-&now();
\$tz = DateTime::TimeZone-&new(
&&name=&"local");
\$tz-&offset_for_datetime(\$dt) /
\$tz-&is_dst_for_datetime(\$dt);
import&time
time.localtime()
time.tzname[tm.tm_isdst]
(time.timezone / -3600) + tm.tm_isdst
tm.tm_isdst
use&Time::HiRes&qw(gettimeofday);
(\$sec, \$usec) =
t.microsecond
a float argument will be truncated to an
import&time
time.sleep(0.5)
&&\$SIG{ALRM}=&sub&{die&"timeout!";};
&&alarm&5;
&&sleep&10;
import&signal, time
class&Timeout(Exception):&pass
def&timeout_handler(signo, fm):
&&raise&Timeout()
signal.signal(signal.SIGALRM,
&&timeout_handler)
&&signal.alarm(5)
&&time.sleep(10)
except&Timeout:
signal.alarm(0)
@a&= (1, 2, 3, 4);
a&= [1, 2, 3, 4]
@a&=&qw(do re mi);
\$#a&+ 1&or
scalar(@a)
\$a[0] =&"lorem";
a[0] =&'lorem'
evaluates as&undef:
increases array
size to 11:
\$a[10] =&"lorem";
raises&IndexError:
raises&IndexError:
a[10] =&'lorem'
use&List::Util&'first';
@a&=&qw(x y z w);
\$i = first {\$a[\$_]&eq&"y"} (0..\$#a);
a&= ['x',&'y',&'z',&'w']
i&= a.index('y')
select 3rd and 4th elements:
splice(@a, 2, 2)
select 3rd and 4th elements:
@a[1..\$#a]
@a&= (6,7,8);
push&@a, 9;
a&= [6,7,8]
a.append(9)
@a&= (6,7,8);
unshift&@a, 5;
a&= [6,7,8]
a.insert(0,5)
@a&= (1,2,3);
@a2&= (@a,(4,5,6));
push&@a, (4,5,6);
a&= [1,2,3]
a2&= a + [4,5,6]
a.extend([4,5,6])
@a&= (undef)&x&10;
a = [None] * 10
a = [None for&i&in range(0, 10)]
use&Storable&'dclone'
my&@a&= (1,2,[3,4]);
my&\$a2&= \@a;
my&@a3&=&@a;
my&@a4&= @{dclone(\@a)};
import&copy
a&= [1,2,[3,4]]
a3&=&list(a)
copy.deepcopy(a)
数组作为函数参数
each element passed
use reference to pass array as single argument
parameter contains address copy
for&\$i&(1, 2, 3) {&print&"\$i\n"&}
for&i&in&[1,2,3]:
&&print(i)
use range iteration from&0&to&\$#a&and
use index to look up value in the loop body
a&= ['do',&'re',&'mi',&'fa']
for&i, s&in&enumerate(a):
&&print('%s at index %d'&% (s, i))
for&\$i&(1..1_000_000) {
range&replaces&xrange&in
for&i&in xrange(1, 1000001):
@a&= 1..10;
a&=&range(1, 11)
a&=&list(range(1, 11))
@a&= (1,2,3);
reverse&@a;
@a&=&reverse&@a;
a&= [1,2,3]
a.reverse()
@a&=&qw(b A a B);
@a&=&sort&@a;
sort&{&lc(\$a)&cmp&lc(\$b) }&@a;
a&= ['b',&'A',&'a',&'B']
a.sort(key=str.lower)
use&List::MoreUtils&'uniq';
my&@a&= (1,2,2,3);
my&@a2&= uniq&@a;
@a&= uniq&@a;
a&= [1,2,2,3]
a2&=&list(set(a))
a&=&list(set(a))
{1,2} & {2,3,4}
{1,2} | {2,3,4}
{1,2,3} - {2}
{1,2} ^ {2,3,4}
map&{ \$_ * \$_ } (1,2,3)
map(lambda&x: x * x, [1,2,3])
list comprehension:
[x*x for x in [1,2,3]]
grep&{ \$_ & 1 } (1,2,3)
filter(lambda&x: x & 1, [1,2,3])
list comprehension:
[x for x in [1,2,3] if x & 1]
use&List::Util&'reduce';
reduce { \$x + \$y } 0, (1,2,3)
# import needed in Python 3 only
from&functools&import reduce
reduce(lambda&x, y: x+y, [1,2,3], 0)
# cpan -i List::MoreUtils
use&List::MoreUtils&qw(all any);
all { \$_ % 2 == 0 } (1,2,3,4)
any { \$_ % 2 == 0 } (1,2,3,4)
all(i%2 == 0&for&i&in&[1,2,3,4])
any(i%2 == 0&for&i&in&[1,2,3,4])
use&List::Util&'shuffle';
@a&= (1, 2, 3,
shuffle(@a);
from&random&import&shuffle, sample
a&= [1, 2, 3, 4]
shuffle(a)
sample(a, 2)
# cpan -i List::MoreUtils
use&List::MoreUtils&'zip';
@nums&= (1, 2, 3);
@lets&=&qw(a b c);
# flat array
of 6 elements:
@a&= zip&@nums,&@lets;
# array of 3 pairs:
a&= zip([1,2,3],
['a',&'b',&'c'])
%d&= (&t&=& 1,&f&=& 0 );
d&= {&'t':1,&'f':0 }
scalar(keys&%d)
evaluates as&undef:
\$d{"lorem"};
adds key/value
\$d{"lorem"} =&"ipsum";
raises&KeyError:
d['lorem']
adds key/value
d['lorem'] =&'ipsum'
exists&\$d{"y"}
%d&= ( 1 =&&"t", 0 =&&"f"&);
delete&\$d{1};
d&= {1:&True, 0:&False}
@a&= (1,"a",2,"b",3,"c");
a&= [[1,'a'], [2,'b'], [3,'c']]
d&=&dict(a)
a&= [1,'a',2,'b',3,'c']
d&=&dict(zip(a[::2], a[1::2]))
%d1&= (a=&1,&b=&2);
%d2&= (b=&3,&c=&4);
%d1&= (%d1,&%d2);
d1&= {'a':1,&'b':2}
d2&= {'b':3,&'c':4}
d1.update(d2)
# {'a': 1, 'c':
4, 'b': 3}
%to_num&= (t=&1,&f=&0);
%to_let&=&reverse&%to_num;
to_num&= {'t':1,&'f':0}
comprehensions added in 2.7:
to_let&= {v:k&for&k, v
&&in&to_num.items()}
while&( (\$k, \$v) =&each&%d&) {
for&k, v&in&d.iteritems():
for&k, v&in&d.items():
d.values()
list(d.keys())
list(d.values())
my&%counts;
\$counts{'foo'} += 1
define a tied
hash for computed values and defaults other than zero or empty string
from&collections&import&defaultdict
counts&= defaultdict(lambda: 0)
counts['foo'] += 1
class&Factorial(dict):
&&def&__missing__(self, k):
&&&&if&k & 1:
&&&&&&return&k *&self[k-1]
&&&&&&return&1
factorial&= Factorial()
sub&add&{&\$_[0] +&\$_[1] }
&&my&(\$a,&\$b) =&@_;
&&\$a + \$b;
def&add(a, b):
&&return&a+b
add(1, 2);
parens are
set to&undef
raises&TypeError
sub&my_log&{
&&my&\$x&=&shift;
&&my&\$base&=&shift&// 10;
&&log(\$x)/log(\$base);
my_log(42);
my_log(42,&exp(1));
import&math
def&my_log(x, base=10):
&&return&math.log(x)/math.log(base)
my_log(42)
my_log(42, math.e)
&&if&(&@_&&= 1 ) {
&&&&print&"first: \$_[0]\n";
&&if&(&@_&&= 2 ) {
&&&&print&"last: \$_[-1]\n";
def&foo(*a):
&&if len(a) &= 1:
&&&&print('first: '&+&str(a[0]))
&&if len(a) &= 2:
&&&&print('last: '&+&str(a[-1]))
def&fequal(x, y, **opts):
&&eps&= opts.get('eps')&or&0.01
&&return abs(x - y) & eps
fequal(1.0, 1.001)
fequal(1.0, 1.001, eps=0.1**10)
&&\$_[0] += 1;
&&\$_[1] .=&"ly";
my&\$n&= 7;
my&\$s&=&"hard";
foo(\$n, \$s);
not possible
&&\$_[0][2] = 5;
&&\$_[1]{"f"} = -1;
my&@a&= (1,2,3);
my&%d&= ("t"=& 1,&"f"&=& 0);
foo(\@a, \%d);
def&foo(x, y):
&&x[2] = 5
&&y['f'] = -1
a&= [1,2,3]
d&= {'t':1,&'f':0}
return&arg or last expression
return&arg or&None
sub&first_and_second&{
&&return&(\$_[0],&\$_[1]);
@a&= (1,2,3);
(\$x, \$y) = first_and_second(@a);
def&first_and_second(a):
&&return&a[0], a[1]
x,&y&= first_and_second([1,2,3])
\$sqr =&sub&{&\$_[0] *&\$_[0] }
body must be an expression:
sqr&=&lambda&x: x * x
\$sqr-&(2)
my&\$func&= \&
func&= add
use&feature&
sub&counter&{
&&state \$i = 0;
print&counter()
# state not private:
def&counter():
&&counter.i += 1
&&return&counter.i
counter.i = 0
print(counter())
sub&make_counter&{
&&my&\$i&= 0;
&&return&sub&{ ++\$i };
my&\$nays&=
print&\$nays-&()
# Python 3:
def&make_counter():
&&def&counter():
&&&&nonlocal i
&&&&i += 1
&&&&return&i
&&return&counter
nays = make_counter()
def&make_counter():
&&while True:
&&&&i += 1
&&&&yield&i
make_counter()
print(nays.next())
def logcall(f):
&&def wrapper(*a, **opts):
&&&&print('calling ' + f.__name__)
&&&&f(*a, **opts)
&&&&print('called ' + f.__name__)
&&return wrapper
def square(x):
&&return x * x
if&( 0 == \$n ) {
&&print&"no
}&elsif&( 1 == \$n ) {
&&print&"one hit\n"
&&print&"\$n
if&0 == n:
&&print('no hits')
elif&1 == n:
&&print('one hit')
&&print(str(n) +&' hits')
use&feature&'switch';
given (\$n) {
&&when (0) {&print&"no
hits\n"; }
&&when (1) {&print&"one
&&default {&print&"\$n
hits\n"; }
while&( \$i & 100 ) { \$i++ }
while&i & 100:
for&( \$i=0; \$i &= 10; \$i++ ) {
&&print&"\$i\n";
@a = (1..5);
foreach& (@a) {
&& print "\$_\n";
@a = (1..5);
for (@a) {
&& print "\$_\n"
a = ['do', 're', 'mi', 'fa']
for i, s in enumerate(a):
& print('%s at index %d' % (s, i))
for i in [1,2,3]:
& print(i)
last next redo
break continue&none
do else elsif for foreach goto if
unless until while
elif else for if while
executes following block and returns
value of last statement executed
raises&NameError&unless a value was
assigned to it
print&"positive\n"&if&\$i & 0;
print&"nonzero\n"&unless&\$i == 0;
die&"bad arg";
raise&Exception('bad arg')
eval&{ risky };
if&(\$@) {
&&print&"risky
failed: \$@\n";
&&print('risky failed')
\$EVAL_ERROR: \$@
\$OS_ERROR:&\$!
\$CHILD_ERROR: \$?
last exception:&sys.exc_info()[1]
class&Bam(Exception):
&&def&__init__(self):
&&&&super(Bam,&self).__init__('bam!')
&&raise&Bam()
except&Bam&as&e:
&&print(e)
acquire_resource()
&&release_resource()
use&threads;
\$func =&sub&{&sleep&10 };
\$thr = threads-&new(\$func);
class&sleep10(threading.Thread):
&&def&run(self):
&&&&time.sleep(10)
thr&= sleep10()
thr.start()
\$thr-&join;
thr.join()
文件和输出
print&"Hello, World!\n";
print('Hello, World!')
\$line = &STDIN&;
line&= sys.stdin.readline()
STDIN STDOUT STDERR
sys.stdin sys.stdout sys.stderr
open&my&\$f,&"/etc/hosts";&or
open&FILE,&"/etc/hosts";
f&=&open('/etc/hosts')
open&my&\$f,&"&/tmp/perl_test";&or
open&FILE,&"&/tmp/perl_test";
f&=&open('/tmp/test',&'w')
with open('/tmp/test')&as&f:
&&f.write('lorem ipsum\n')
close&\$f;&or
close&FILE;
\$line = &\$f&;&or
\$line = &FILE&;
f.readline()
while&(\$line = &\$f&) {
for&line&in&f:
line&= line.rstrip('\r\n')
@a&= &\$f&;
\$s = do { local \$/; &\$f& };
a&= f.readlines()
s&= f.read()
print&\$f&"lorem ipsum";
f.write('lorem ipsum')
use&IO::Handle;
\$f-&flush();
If (-e&"/etc/hosts") {}
-f&"/etc/hosts"
os.path.exists('/etc/hosts')
os.path.isfile('/etc/hosts')
use&File::Copy;
copy("/tmp/foo",&"/tmp/bar");
unlink&"/tmp/foo";
move("/tmp/bar",&"/tmp/foo");
import&shutil
shutil.copy('/tmp/foo',&'/tmp/bar')
os.remove('/tmp/foo')
shutil.move('/tmp/bar',&'/tmp/foo')
os.remove()
chmod&0755,&"/tmp/foo";
os.chmod('/tmp/foo', 0755)
use&File::Temp;
\$f = File::Temp-&new();
print&\$f&"lorem ipsum\n";
close \$f;
print&"tmp file:
print&\$f-&filename
import&tempfile
f&= tempfile.NamedTemporaryFile(
&&prefix='foo')
f.write('lorem ipsum\n')
print("tmp file: %s"&% f.name)
my&(\$f,&\$s);
open(\$f,&"&", \\$s);
print&\$f&"lorem ipsum\n";
from&StringIO&import&StringIO
f&= StringIO()
f.write('lorem ipsum\n')
s&= f.getvalue()
Python 3 moved&StringIO&to
the&io&module
use&File::Spec;
File::Spec-&catfile("/etc",&"hosts")
os.path.join('/etc',&'hosts')
use&File::Basename;
print&dirname("/etc/hosts");
print&basename("/etc/hosts");
os.path.dirname('/etc/hosts')
os.path.basename('/etc/hosts')
Cwd::abs_path("..")
os.path.abspath('..')
use&File::Basename;
while&(&&/etc/*&&) {
&&&print&basename(\$_)
for&filename&in&os.listdir('/etc'):
&&print(filename)
use&File::Path&'make_path';
make_path&"/tmp/foo/bar";
dirname&=&'/tmp/foo/bar'
if not&os.path.isdir(dirname):
&&os.makedirs(dirname)
# cpan -i File::Copy::Recursive
use&File::Copy::Recursive&'dircopy';
dircopy&"/tmp/foodir",
&&"/tmp/bardir";
import&shutil
shutil.copytree('/tmp/foodir',
&&'/tmp/bardir')
rmdir&"/tmp/foodir";
os.rmdir('/tmp/foodir')
use&File::Path&'remove_tree';
remove_tree&"/tmp/foodir";
import&shutil
shutil.rmtree('/tmp/foodir')
os.path.isdir('/tmp')
命令行操作
scalar(@ARGV)
\$ARGV[0]&\$ARGV[1]&etc
len(sys.argv)-1
sys.argv[1] sys.argv[2]&etc
sys.argv[0]
use&Getopt::Long;
my&(\$src,&\$help);
sub&usage&{
&&print&"usage: \$0&--f
&&exit&-1;
GetOptions("file=s"&=& \\$src,
&&"help"&=& \\$help);
usage&if&\$
import&argparse
argparse.ArgumentParser()
parser.add_argument('--file',&'-f',
&&dest='file')
parser.parse_args()
src&= args.file
\$ENV{"HOME"}
\$ENV{"PATH") =&"/bin";
os.getenv('HOME')
os.environ['PATH'] =&'/bin'
sys.exit(0)
\$SIG{INT} =&sub&{
&&die&"exiting…\n";
import&signal
def&handler(signo, frame):
&&print('exiting…')
signal.signal(signal.SIGINT, handler)
-x&"/bin/ls"
os.access('/bin/ls', os.X_OK)
system("ls -l /tmp") == 0&or
if&os.system('ls -l /tmp'):
&&raise&Exception('ls failed')
\$path = &&;
chomp(\$path);
system("ls",&"-l", \$path) == 0&or
import&subprocess
cmd&= ['ls',&'-l',&'/tmp']
if&subprocess.call(cmd):
&&raise&Exception('ls failed')
my&\$files&=&`ls -l /tmp`;&or
my&\$files&=&qx(ls);
import&subprocess
cmd&= ['ls',&'-l',&'/tmp']
files&= subprocess.check_output(cmd)
__________________________________________
感谢,Thanks!
本文版权归作者iTech所有,转载请包含作者签名和出处,不得用于商业用途,非则追究法律责任!
转载本文请联系原作者获取授权,同时请注明本文来自穆跃文科学网博客。链接地址:
上一篇:下一篇:
当前推荐数:0
评论 ( 个评论)
扫一扫,分享此博文
作者的其他最新博文
热门博文导读
Powered by
Copyright &Boolean values in Perl
Introduction
Lists and Arrays
Subroutines
Hashes, arrays
Regular Expressions
Perl and Shell related functionality
Few examples for using Perl
Common warnings and error messages
Search for '{{search_term}}'
Boolean values in Perl
Perl does not have a special boolean type and yet,
in the documentation of Perl you can often see that a function returns a "Boolean" value.
Sometimes the documentation says the function returns true or returns false.
So what's the truth?
Perl does not have specific boolean type, but every scalar value - if checked using if
will be either true or false. So you can write
if ($x eq "foo") {
and you can also write
the former will check if the content of the $x variable is the same as the "foo"
string while the latter will check if $x itself is true or not.
What values are true and false in Perl?
It is quite easy. Let me quote the documentation:
The number 0, the strings '0' and '', the empty list "()", and "undef"
are all false in a boolean context. All other values are true.
Negation of a true value by "!" or "not" returns a special false
value. When evaluated as a string it is treated as '', but as a number, it is treated as 0.
From perlsyn under "Truth and Falsehood".
So the following scalar values are considered false:
undef - the undefined value
the number 0, even if you write it as 000
the empty string.
the string that contains a single 0 digit.
All other scalar values, including the following are true:
1 any non-0 number
the string with a space in it
two or more 0 characters in a string
a 0 followed by a newline
yes, even the string 'false' evaluates to true.
I think this is because ,
creator of Perl, has a general positive world-view.
He probably thinks there are very few bad and false things in the world.
Most of the things are true.
Written by
In the comments, please wrap your code snippets within &pre& &/pre& tags and use spaces for indentation.
Please enable JavaScript to view the

我要回帖

更多关于 mysql true false 0 1 的文章

 

随机推荐