Attention, cette page n'est plus maintenue. Seules les notions de base restent valables.
Ceci est mon aide-mémoire PHP-Perl-Python-Javascript-Java. Il permet, par exemple, de retrouver le "file_get_contents" de PHP à partir du "urllib2" de Python, ou l'inverse.
Quelques précisions sur ce document :
tout afficher >> | PHP 5cacher | Perl 5cacher | Python 2cacher | Javascript ES5cacher | Java 7cacher |
essais |
php -a |
re.pl |
python |
F12 ou Shift-Ctl-K dans Firefox 11+ |
dans eclipse : Ctl-F11 |
valider la syntaxe |
php -l script.php |
perl -c script.pl |
pychecker script.py |
JSLint |
(dans eclipse, automatique) |
doc rapide |
php.net |
man perlintro man perltoc man perlfunc man perlvar man perlre ... perldoc -f sort |
Google : python ... doc officielle ou pour voir les fonctions d'un module : import string dir(string) |
Google : MDN javascript |
Google : java ... doc officielle |
$a = 123; |
$a = 123; |
a = 123 |
a = 123; |
int a = 123; |
|
$a++; ++$a; |
$a++; ++$a; |
a += 1 |
a++; ++a; |
a++; ++a; |
|
$a /= 2; # 62.5 |
$a /= 2; # 62.5 |
a /= 2 # 62 a /= 2.0 # 62.5 |
a /= 2; // 62.5 |
a /= 2; // 62 float b = (float) a / 2; // 62.5 |
|
modulo |
$a = 5 % 2; |
$a = 5 % 2; |
a = 5 % 2 |
a = 5 % 2; |
int a = 5 % 2; |
typage |
$a = 1; $a += "b"; # OK |
$a = 1; $a += "b"; # OK |
a = 1 a += 'b' # erreur d'exécution "TypeError" |
a = 1; a += "b"; // OK |
int a = 1; a += "b"; // erreur de compilation "inconvertible types" |
if ... |
if ($a == 1) { echo "un"; } elseif ($a == 2) { echo "deux"; } else { echo "je n'sais pas"; } |
if ($a == 1) { print "un"; } elsif ($a == 2) { print "deux"; } else { print "je n'sais pas"; } |
if a == 1: print 'un' elif a == 2: print 'deux' else: print "je n'sais pas" |
if (a == 1) { alert("un"); } else if (a == 2) { alert("deux"); } else { alert("je n'sais pas"); } |
if (a == 1) { System.out.println("un"); } else if (a == 2) { System.out.println("deux"); } else { System.out.println("je n'sais pas"); } |
switch |
switch($a) { case 1: echo "un"; break; case 2: echo "deux"; break; default: echo "je ne sais pas"; } |
# à partir de Perl 5.10 : use feature ":5.10"; given($a) { when(1) { print "un"; } when(2) { print "deux"; } default { print "je ne sais pas"; } } # avant 5.10, utiliser un bloc (man perlsyn) |
# sans équivalent # utiliser if elif elif else |
switch(a) { case 1: alert("un"); break; case 2: alert("deux"); break; default: alert("je ne sais pas"); } |
switch(a) { case 1: System.out.println("un"); break; case 2: System.out.println("deux"); break; default: System.out.println("je ne sais pas"); } |
particularité Perl |
if ($a == 2) { echo "deux"; } elseif ($a == 'deux') { echo "deux en toutes lettres"; } else { echo "... je ne sais pas"; } |
if ($a == 2) { print "deux"; } elsif ($a eq 'deux') { print "deux en toutes lettres"; } else { print "... je ne sais pas"; } # l'inverse de eq : if ($a ne 'trois') ... |
if a == 2: print 'deux' elif a == 'deux': print 'deux en toutes lettres' else: print '... je ne sais pas' |
if (a == 2) { alert("deux"); } else if (a == "deux") { alert("deux en toutes lettres"); } else { alert("je n'sais pas"); } |
// sans objet : typage fort // à part ça, pour les chaînes de caractères : if ("deux".equals(a)) { |
particularité PHP et JS |
if ($a === "2") { echo "égaux et du même type"; } elseif ($a == "2") { echo "égaux (avec conversion)"; } else { echo "pas égaux"; } # l'inverse de === est !== |
# sans équivalent ? |
# sans objet : typage fort |
if (a === "2") { alert("égaux et du même type"); } else if (a == "2") { alert("égaux (avec conversion)"); } else { alert("pas égaux"); } // l'inverse de === est !== |
// sans objet : typage fort |
variable non initialisée |
if (!isset($b)) { echo '$b non initialisée !'; echo $b; // PHP Notice: Undefined variable } |
if (! defined $b) { print '$b non initialisée !'; print $b; # par défaut, pas d'erreur ! } # mais avec use warnings; ou perl -w # Use of uninitialized value $b ... |
try: print b except NameError: print 'b non-initialisée' print b # NameError: name 'b' is not defined |
if (typeof b == 'undefined') { alert("b non initialisée"); alert(b); // ReferenceError: b is not defined } |
// normalement, ça ne compile pas // "variable may not have been initialized" // sauf avec un membre de classe // de type primitif, comme boolean, int, etc. // ou de type String public class Exemple { private int b; public void foo() { System.out.println(b); // affiche 0 } } // avec String, ça affiche "null". // si b variable locale, ça ne compile pas. |
commenter |
// une ligne # une ligne /* plusieurs lignes */ |
# une ligne |
# une ligne ''' plusieurs lignes ''' |
// une ligne /* plusieurs lignes */ |
// une ligne /* plusieurs lignes */ |
afficher sans passer à la ligne |
echo abs(-4); |
print abs -4; # ou print abs(-4); |
import sys sys.stdout.write(str(abs(-4))) # plus simple mais avec un espace en bout de ligne : print abs(-4), |
document.write(Math.abs(-4)); | System.out.print(Math.abs(-4)); |
en passant à la ligne |
echo abs(-4)."\n"; |
print abs(-4)."\n"; # ou : local $\ = "\n"; print abs(-4); |
print abs(-4) |
document.writeln(Math.abs(-4)); // ou write(4 + "\n"); |
System.out.println(Math.abs(-4)); // ou print(Math.abs(-4) + "\n"); |
particularité Python | ? | ? | a = '''ligne 1 ligne 2''' print repr(a) # affiche 'ligne 1\nligne 2' |
? | ? |
écrire sur la sortie d'erreur | fwrite(STDERR, "oups\n"); | print STDERR "oups\n"; |
import sys sys.stderr.write("oups\n") |
console.error("oups"); | System.err.println("oups"); |
booléens |
$a = TRUE; # true, True, TrUe ... |
$a = 1; # tout sauf 0, undef, "" |
a = True |
a = true; |
boolean a = true; |
opérateurs logiques |
if (1 && 1) { echo "vrai\n"; } if (1 and 1) { echo "idem\n"; } if (1 || 0) { echo "vrai aussi\n"; } if (1 or 0) { echo "idem\n"; } |
if (1 && 1) { print "vrai\n"; } if (1 and 1) { print "idem\n"; } if (1 || 0) { print "vrai aussi\n"; } if (1 or 0) { print "idem\n"; } |
if True and True: print "vrai" if True or False: print "vrai aussi" |
if (true && true) { alert("vrai"); } if (true || false) { alert("vrai aussi"); } |
if (true && true) { System.out.println("vrai"); } if (true || false) { System.out.println("vrai aussi"); } |
chaîne de caractères |
$a = "test"; $a = 'test'; |
$a = "test"; $a = 'test'; |
a = "test" a = 'test' # préféré par convention |
a = "test"; a = 'test'; |
String a = "test"; // guillemet simple réservé au type caractère |
echo $a[2]; // ou $a{2} |
print a[2] |
alert(a.charAt(2)); |
TODO |
||
concaténation |
$a .= "foo"; |
$a .= "foo"; |
a += "foo" |
a += "foo"; |
a += "foo"; // mais pour de nombreuses concaténations, il y a plus performant : StringBuilder a = new StringBuilder("test"); a.append("foo"); System.out.println(a); |
echo strlen($a); // pour Unicode : echo mb_strlen($a); // ou encore : echo grapheme_strlen($a) |
print length $a; # ou print length($a); |
print len(a) |
alert(a.length); |
System.out.println(a.length()); |
|
code caractères |
for ($i = 0; $i < strlen($a); $i++) { echo ord($a[$i])."\n"; } |
print join("\n", unpack("W*", $a)); # use utf8 et unpack("U*"... si utf8 # ou for (0..length($a)-1) { print ord(substr($a, $_, 1))."\n"; } |
for c in a: print ord(c) |
for (i in a) { alert(a.charCodeAt(i)); } |
TODO |
normaliser les accents du Mac de 3 octets en 2 octets | echo normalizer_normalize('é', Normalizer::FORM_C ); | import unicodedata print unicodedata.normalize('NFC', u'é') |
|||
"stf" |
echo substr($a,2,3); // pour UTF-8 : mb_substr('hé !',1,1,'UTF-8'); |
print substr $a,2,3; # ou print substr($a,2,3); |
print a[2:5] |
alert(a.substring(2,5)); // start, stop // ou alert(a.substr(2,3)); // start, length // voir aussi slice() |
System.out.println(a.substring(2, 5)); |
"tfoo" |
echo substr($a,3); | print substr($a,3); |
print a[3:] |
alert(a.substring(3)); // ou alert(a.substr(3)); |
System.out.println(a.substring(3)); |
"testf" |
echo substr($a,0,-2); | print substr($a,0,-2); |
print a[:-2] | alert(a.substring(0,a.length - 2)); | System.out.println(a.substring(0,a.length()-2)); |
echo strtoupper($a); // pour de l'UTF-8 : echo mb_strtolower('HÉ !', 'UTF-8'); |
print uc($a); # ou uc $a; | print a.upper() | alert(a.toUpperCase()); |
System.out.println(a.toUpperCase()); | |
"Testfoo" |
echo ucfirst($a); |
print ucfirst($a); # ou print ucfirst $a; |
print a[0].upper() + a[1:] |
alert(a.charAt(0).toUpperCase()+a.substr(1)); | System.out.println(a.substring(0,1).toUpperCase() +
a.substring(1)); |
echo ucwords("jorge luis borges"); // pour UTF-8 : echo mb_convert_case('évariste galois', MB_CASE_TITLE, 'UTF-8'); |
# pas d'équivalent => s/\b(\w)/\u$1/g |
print "jorge luis borges".title() | |||
chaîne de caractères sur plusieurs lignes | echo "voici une ". "très longue ". "phrase"; |
print "voici une ". "très longue ". "phrase"; |
print ( 'voici une ' 'très longue ' 'phrase' ) |
alert("voici une " + "très longue " + "phrase"); |
System.out.println("voici une " + "très longue " + "phrase"); |
if (strpos("hervérenault.fr", "a") > -1) { echo "a y est\n"; } |
if (index("hervérenault.fr", "a") > -1) { print "a y est\n"; } |
if 'a' in 'hervérenault.fr': print 'a y est' |
if ("hervérenault.fr".indexOf("a") > -1) { alert("a y est"); } // note : IE8 n'a pas indexOf // utiliser jQuery.inArray() |
if ("hervérenault.fr".indexOf("a") > -1) { System.out.println("a y est"); } |
|
if (strpos("hervérenault.fr", "foo") === false)
{ echo "pas foo\n"; } |
if (index("hervérenault.fr", "foo") == -1) { print "pas foo\n"; } |
if 'foo' not in 'hervérenault.fr': print 'pas foo' |
if ("hervérenault.fr".indexOf("foo") == -1) { alert("pas foo"); } |
if ("hervérenault.fr".indexOf("foo") == -1) { System.out.println("pas foo"); } |
|
supprimer le retour à la ligne en fin de chaîne |
$a = "bonjour\n"; $a = rtrim($a, "\n"); print "$a !\n"; |
$a = "bonjour\n"; chomp($a); # ne supprime qu'un "\n" à la fois print "$a !\n"; |
a = "bonjour\n" a = a.rstrip('\n') print a + " !" |
// à partir d'IE10 ? if (String.prototype.trim) { alert("bonjour\n".trim() + " !"); } // sinon, aveec une regexp : a = "bonjour\n".replace(/\n/,""); alert(a + " !"); // ou jQuery.trim() |
String a = "bonjour\n"; a = a.trim(); System.out.println(a + " !"); |
supprimer les blancs avant et après |
$a = " bonjour \t "; echo "[".trim($a)."]"; |
$a = " bonjour \t "; $a=~s/^\s+|\s+$//g; print "[$a]"; |
a = ' bonjour \t ' print '[' + a.strip(' \t') + ']' # espace et tab d'un coup |
idem précédent |
String a = " bonjour \t "; a = a.trim(); System.out.println("[" + a + "]"); |
formatage |
printf("%s a %d ans\n", "Jean", 60); | printf("%s a %d ans\n", "Jean", 60); |
print '%s a %d ans' % ('Jean', 60) # ou print '{0} a {1} ans'.format('Jean', 60) # ou print '{nom} a {age} ans'.format(nom='Jean', age=60) # attention, tuple obligatoire ! a = ['Jean', 60] print '%s a %d ans' % a # TypeError: not enough arguments ... print '%s a %d ans' % tuple(a) # corollaire print 'foo %s bar' % a # foo ['Jean', 60] bar # pas vraiment ce qu'on veut... |
utiliser une librairie |
System.out.printf("%s a %d ans\n", "Jean", 60); |
$s = sprintf("%s a %d ans\n", "Jean", 60); | $s = sprintf("%s a %d ans\n", "Jean", 60); |
s = "%s a %d ans" % ("Jean", 60) # ou : s = "{0} a {1} ans".format("Jean", 60) |
utiliser une librairie | String s = String.format("%s a %d ans\n", "Jean", 60); |
|
regular expressions (regexps) |
$botte_de_foin = "Jean a 60 ans"; $aiguille = "Jean"; if (preg_match("/$aiguille/", $botte_de_foin)) { echo "trouvé $aiguille...\n"; } |
$botte_de_foin = "Jean a 60 ans"; $aiguille = "Jean"; if ($botte_de_foin =~ /${aiguille}/) { print "trouvé $aiguille...\n"; } |
import re botte_de_foin = 'Jean a 60 ans' aiguille = 'Jean' if re.search(aiguille, botte_de_foin): print 'trouvé', aiguille, '...' |
botte_de_foin = 'Jean a 60 ans'; aiguille = 'Jean'; if (botte_de_foin.match(aiguille)) { alert("trouvé " + aiguille + "..."); } |
String botteDeFoin = "Jean a 60 ans"; String aiguille = "Jean"; Pattern p = Pattern.compile(aiguille); Matcher m = p.matcher(botteDeFoin); if (m.find()) { System.out.println("trouvé " + aiguille + "..."); } |
extraire des groupes d'une regexp |
$a = "Jean a 60 ans"; if (preg_match("/([A-Z].*?) /", $a, $m)) { echo $m[1]; } |
$a = "Jean a 60 ans"; $a =~ /([A-Z].*?) / and print $1; |
import re a = 'Jean a 60 ans' m = re.search('([A-Z].*?) ', a) if m: print m.group(1) |
a = "Jean a 60 ans"; m = a.match("([A-Z].*?) "); if (m) { alert(m[1]); } |
String a = "Antoine a 60 ans"; Pattern p = Pattern.compile("([A-Z].*?) "); Matcher m = p.matcher(a); if (m.find()) { System.out.println(m.group(1)); } |
extraire toutes les occurences d'une regexp |
$a = "Jean est plus vieux que Jérome et Jacques"; preg_match_all("/J\w+/u", $a, $m); print_r($m); # Note: /u pour que \w matche é |
TODO | TODO | TODO | TODO |
substitutions |
$a = preg_replace('/^\w+/', "Antoine", $a); echo $a; |
$a =~ s/^\w+/Antoine/; print $a; |
import re print re.sub('^\w+', 'Antoine', a) # ou : s = re.compile('^\w+') print s.sub('Antoine', a) |
a = a.replace(/^\w+/, "Antoine"); alert(a); |
Pattern p = Pattern.compile("^\\w+"); Matcher m = p.matcher(a); System.out.println(m.replaceFirst("Antoine")); |
avec backreference (référence arrière) | echo preg_replace("/^(\w+)/", "Mon voisin $1", $a); | $a=~s/^(\w+)/Mon voisin \1/g; print $a; |
import re print re.sub('^(\w+)', r'Mon voisin \1', a) # utiliser r'...' sinon \1 produit un effet de bord |
alert( a.replace(/^(\w+)/, "Mon voisin $1") ); |
TODO |
nombre de "a" substitués par "?" (2) |
preg_replace('/a/', "?", $a, -1, $count); echo $count; |
print $a =~ s/a/?/g; |
import re s = re.compile('a') z, c = s.subn('?', a) print c |
// en deux étapes m = a.match(/a/g); a = a.replace(/a/g, "?"); alert(m.length); |
// pas d'équivalent direct : Pattern p = Pattern.compile("a"); Matcher m = p.matcher(a); int c = 0; while (m.find()) { c++; } a = m.replaceAll("?"); System.out.println(c); |
idem en ignorant la casse (3) |
preg_replace('/a/i', "?", $a, -1, $count); echo $count; |
print $a =~ s/a/?/ig; | import re s = re.compile('a', re.IGNORECASE) z, c = s.subn('?', a) print c |
m = a.match(/a/ig); a = a.replace(/a/ig, "?"); alert(m.length); |
Pattern p = Pattern.compile("a", Pattern.CASE_INSENSITIVE); // etc... |
matcher tout y compris un passage à la ligne (\n) |
$a="Voici une ligne et puis deux et voilà"; $a = preg_replace('/une.*?deux/s', "", $a); echo $a; |
$a="Voici une ligne et puis deux et voilà"; $a=~s/une.*?deux//s; print $a; |
import re a="""Voici une ligne et puis deux et voilà""" s = re.compile('une.*?deux', re.DOTALL) print s.sub('', a) |
a="Voici une ligne\net puis deux et voilà"; a = a.replace(/une[\s\S]*?deux/, ""); alert(a); |
String a = "Voici une ligne \net puis deux et voilà"; Pattern p = Pattern.compile("une.*?deux", Pattern.DOTALL); Matcher m = p.matcher(a); System.out.println(m.replaceAll("")); |
particularité PHP |
// pour matcher de l'UTF-8 $a = "HÉ !"; echo preg_replace('/é/iu', 'a', $a); |
||||
chaîne contenant un nombre ? |
$a = "123.45"; if (is_numeric($a)) { echo "ça ressemble à un nombre"; } |
TODO |
import re a = '123.45' # a.isdigit() renvoie False... donc : if re.search('^\d+(\.\d+)?$', a): # moins puissant print 'ça ressemble à un nombre' |
var a = '123.45'; if (!isNaN(a)) { alert('ça ressemble à un nombre'); } |
|
variable contenant un entier ? |
$a = 123; if (is_int($a)) { echo "c'est un entier"; } |
TODO |
a = 123 if isinstance(a, int): print "c'est un entier" |
TODO |
|
un décimal ? |
$a = 123.45; if (is_float($a)) { echo "c'est un décimal"; } |
TODO |
a = 123.45 if isinstance(a, float): print "c'est un décimal" |
TODO |
|
boucle |
for ($x = 2; $x < 6; $x++) { echo "$x\n"; } // ou foreach (range(2, 5) as $x) { echo "$x\n"; } |
for $x (2..5) { # for ou foreach print "$x\n"; } |
for x in xrange(2, 6): print x |
for (var x = 2; x < 6; x++) { alert(x); } |
for (int x = 2; x < 6; x++) { System.out.prinln(x); } |
echo str_repeat(".", 3); |
print "." x 3; |
print '.' * 3 # note: idem en Ruby |
|||
saute 3 arrête à 10 |
$a=0; while(true) { $a++; if ($a == 3) continue; if ($a > 10) break; echo "$a\n"; } |
while (1) { $a++; next if $a == 3; last if $a > 10; print "$a\n"; } |
a=0 while True: a += 1 if a == 3: continue if a > 10: break print a |
int a = 0; while(true) { a++; if (a == 3) continue; if (a > 10) break; System.out.println(a); } |
|
particularité Python |
i = 1 while i < 4: print i i += 1 if i > 10: break # ça n'arrivera pas else: print "la boucle s'est terminée normalement" # exemple inverse : for i in xrange(10): print i if i > 3: break # on interrompt la boucle else: print "fini" # donc ceci ne s'exécutera pas |
||||
liste hétérogène |
$a = array(1, 2, 'foo', 'bar'); // à partir de PHP 5.4 : // $a = [1, 2, 'foo', 'bar']; |
@a = (1, 2, 'foo', 'bar'); | a = [1, 2, 'foo', 'bar'] |
a = [1, 2, 'foo', 'bar']; // ou a = new Array(1, 2, 'foo', 'bar'); // ou a = Array(1, 2, 'foo', 'bar'); |
// impossible : typage fort, soit liste d'entiers, soit liste de
chaines mais pas de mélange |
liste homogène |
$a = array(1, 2, 3, 4); |
@a = (1, 2, 3, 4); |
a = [1, 2, 3, 4] | a = [1, 2, 3, 4]; // ou avec Array() |
List<Integer> a = new ArrayList<Integer>(); Integer[] z = {1, 2, 3, 4}; Collections.addAll(a, z); // ou : Integer[] z = {1, 2, 3, 4}; List<Integer> a = new ArrayList<Integer>(Arrays.asList(z)); |
particularité perl |
@a = qw(foo bar blah); # plus concis que @a = ('foo', 'bar', 'blah'); |
||||
echo $a[2]; |
print $a[2]; |
print a[2] |
alert(a[2]); |
System.out.println(a.get(2)); |
|
$a[] = 5; // ou array_push($a, 5); |
push @a, 5; |
a.append(5) |
a.push(5); |
a.add(5); | |
if (in_array(3, $a)) { echo "3 y est\n"; } |
if (grep $_ == 3, @a) { echo "3 y est\n"; } |
if 3 in a: print "3 y est" |
if (a.indexOf(3) > -1) { alert("3 y est"); } |
# pas d'équivalent |
|
foreach ($a as $b) { echo $b; } |
foreach $b (@a) { print $b; } # ou for $b (@a) { print $b; } |
for b in a: print b |
// pas tout à fait pareil for (b in a) { alert(a[b]); } // seulement à partir de IE9 : a.forEach(function(b) { alert(b); }); |
for (int b : a) { System.out.println(b); } |
|
particularité Perl |
foreach (@a) { print $_; } # ou même, carrément ! foreach (@a) { print; } |
||||
liste d'affectations |
list($b, $c, $d) = $a; # le 4 est ignoré # swap : list($b, $c) = array($c, $b); |
($b, $c, $d) = @a; # le 4 est ignoré # swap : ($b, $c) = ($c, $b); |
b, c, d, e = a # on ne peut pas ignorer le 4 # swap : b, c = c, b |
// KO dans IE |
// impossible |
type |
if (is_array($a)) { echo "array"; } |
# le type est porté par le nom de variable # sauf si c'est une référence (voir dessous) |
if isinstance(a, list): print "list" |
if (a instanceof Array) { alert("Array"); } |
if (a instanceof ArrayList) { System.out.println("ArrayList"); } // ou : if (a.getClass() == java.util.ArrayList.class) |
join |
$b = join(", ", $a); // ou $b = implode(", ", $a); |
$b = join(", ", @a); |
b = ", ".join(a) # si a contient autre chose que des 'str' : b = ", ".join(str(x) for x in a) |
b = a.join(", "); |
StringBuilder sb = new StringBuilder(); Iterator<Integer> it = a.iterator(); while (it.hasNext()) { sb.append(it.next()); if (it.hasNext()) { sb.append(", "); } } String b = sb.toString(); |
split |
$a = explode(", ", $b); // pas de regexp ! // ou $a = preg_split('/, /', $b); // mais pas split : obsolète depuis 5.3 |
@a = split(/, /, $b); |
a = b.split(", ") # si on veut retrouver des 'int' : b = [int(x) for x in b.split(", ")] |
a = b.split(", "); // ou a = b.split(/, /); |
List<Integer> a = new ArrayList<Integer>(); for (String x : b.split(", ")) { a.add(Integer.parseInt(x)); } |
variante |
list($c, $d, $reste) = split(", ", $b, 3); |
($c, $d, $reste) = split(/, /, $b, 3); |
(c, d, reste) = b.split(", ", 2) # /!\ limite N-1 pour N éléments |
String[] b2 = b.split(", ", 3); String c = b2[0], d = b2[1], reste = b2[2]; |
|
echo $a; # affiche Array |
print @a; # affiche 1234 # sauf si local $, = ", "; print @a; # affiche 1, 2, 3, 4 |
print a # affiche [1, 2, 3, 4] |
alert(a); |
System.out.println(a); // affiche [1, 2, 3, 4] |
|
print_r($a); # ou plus précis : var_dump($a); |
use Data::Dumper; print Dumper(@a); |
print a |
console.log(a); // ou plus basique : for (b in a) { alert(b + ' => ' + a[b]); } |
||
echo $a[1]; |
print $a[1]; |
print a[1] |
alert(a[1]); |
System.out.println(a.get(1)); |
|
echo count($a); |
print scalar(@a); |
print len(a) |
alert(a.length); |
System.out.println(a.size()); |
|
echo $a[count($a) -1]; # ou echo end($a); |
print $a[$#a]; |
print a[-1] |
alert(a[a.length -1]); |
System.out.println(a.get(a.size() - 1)); |
|
$b = array(1,1,1,2,3,3,4); $b = array_unique($b) print_r($b); # affiche : Array ( [0] => 1 [3] => 2 [4] => 3 [6] => 4 ) # attention, $b[1] n'existe plus ! |
# avec un hash : @b = (1,1,1,2,3,3,4); foreach (@b) { if (! $c{$_}) { push(@d, $_); $c{$_}++; } } print join(", ", @d); # affiche : 1, 2, 3, 4 # ou avec un module use List::MoreUtils qw(uniq); print join(", ", uniq @b); |
b = [1,1,1,2,3,3,4] print set(b) # affiche : set([1, 2, 3, 4]) # ou encore : b = list(set(b)) |
Integer[] bi = {1,1,1,2,3,3,4}; List<Integer> b = new ArrayList<Integer>(Arrays.asList(bi)); Set<Integer> c = new HashSet<>(b); List<Integer> d = new ArrayList<Integer>(c); System.out.println(d); // affiche : [1, 2, 3, 4] |
||
liste non modifiable |
# sans équivalent ? | # sans équivalent ? | a = (1, 2, "foo", "bar") # un "tuple", pas une "liste" ! |
// sans équivalent ? | |
listes dynamiques imbriquées |
$a = array(1,2,3,array(4,5),6,7); |
@a=(1,2,3,[4,5],6,7); |
a=[1,2,3,[4,5],6,7] |
a=[1,2,3,[4,5],6,7]; | TODO |
hash (table de hachage, "dictionnaire" en Python, "associative
array" en PHP) |
$a = array("foo" => 3, "bar" => 4, "baz" => NULL); |
%a = ("foo" => 3, "bar" => 4, "baz" => undef); # ou %a = ("foo", 3, "bar", 4, "baz", undef); |
a = { "foo" : 3, "bar" : 4, "baz" : None } # ou a = dict([("foo", 3), ("bar", 4), ("baz", None)]) |
a = { "foo" : 3, "bar" : 4, "baz" : null }; // a est un objet // "foo" est une propriété // a n'est pas ordonné |
Map<String, Integer> a = new HashMap<String,
Integer>(); a.put("foo", 3); a.put("bar", 4); a.put("baz", null); |
echo $a["foo"]; | print $a{"foo"}; | print a["foo"] # ou print a.get("foo") # ou print a.get("foo", "bar") # Si la clé "foo" n'existait pas : # a["foo"] provoquerait une erreur KeyError # a.get("foo") renverrait None # a.get("foo", "bar") renverrait "bar" |
alert(a["foo"]); // ou alert(a.foo); |
System.out.println(a.get("foo")); |
|
taille d'un objet |
echo count($a); # ou echo sizeof($a); |
print scalar(%a); | print len(a) |
// à partir d'IE9 : alert(Object.keys(a).length); // sinon : size = 0; for (k in a) { size++; } alert(size); // ou : Object.size = function(o) { var size = 0; for (k in o) { size++; } return size; } alert(Object.size(a)); // mais pas ça, qui ajoute "size" à toute // boucle for (... in ...) ! var size = 0; for (k in this) { // pour ne pas compter size ! if (this.hasOwnProperty(k)) { size++; } } return size; } alert(a.size()); // ou avec jQuery : .size() et .length |
|
if (! array_key_exists("truc", $a)) { echo "clé truc n'existe pas\n"; } |
if (! exists($a{"truc"})) { print "clé truc n'existe pas\n"; } |
if "truc" not in a: print "clé truc n'existe pas" # avant Python 3 on avait aussi has_key() # if not a.has_key("truc"): |
if (a["truc"] === undefined) { alert("clé truc n'existe pas"); } // ou if (!a.hasOwnProperty("truc")) |
if (! a.containsKey("truc")) { System.out.println("clé truc n'existe pas"); } |
|
if ($a["baz"] == null) { echo "pas de valeur associée à baz\n"; } // si pas de clé, PHP Notice: Undefined index // attention ! if (!isset($a["baz"])) { echo "pas de clé OU de valeur associée !\n"; } // attention++ ! if (empty($a["baz"])) { echo "idem OU valeur 0 ou chaine vide\n"; } |
if (! defined($a{"baz"})) { print "pas de clé OU de valeur associée à baz\n"; } |
if not a["baz"]: print "pas de valeur associée à baz" # si pas de clé, KeyError |
if (a["baz"] === null) { alert("pas de valeur associée à baz"); } // attention ! if (a["baz"] == undefined) { alert("pas de clé OU de valeur associée !"); } // idem : if (a["baz"] == null) { alert("pas de clé OU de valeur associée"); } |
if (a.get("baz") == null) { System.out.println("pas de clé OU de valeur associée à baz"); } |
|
foreach ($a as $k => $v) { echo "$k => $v\n"; } // ou reset($a); while (list($k, $v) = each($a)) { echo "$k => $v\n"; } |
foreach $k (keys %a) { print "$k => $a{$k}\n"; } # ou while (($k, $v) = each %a) { print "$k => $v\n"; } |
for k, v in a.iteritems(): print k, "=>", v # iteritems est préférable à items # pour une itération # même si on peut utiliser items # (qui construit une liste) |
for (k in a) { alert(k + " => " + a[k]); } |
for (String k : a.keySet()) { System.out.println(k + " => " + a.get(k)); } |
|
unset($a["foo"]); |
delete $a{"foo"}; # /!\ undef $a{"foo"}; # n'efface que la valeur ! |
del a["foo"] |
delete a["foo"]; |
a.remove("foo"); |
|
particularité python : setdefault() | a = { 'foo': 123, 'truc': 456 } print a.setdefault('foo', 'x') # affiche 123 print a.setdefault('bidule', 'x') # affiche x # et maintenant a['bidule'] vaut 'x' # autre cas plus classique : a = { 'foo': 123, 'truc': 456 } for k in ['foo', 'truc', 'bidule']: if k not in a: a[k] = 'x' # se remplace par : a = { 'foo': 123, 'truc': 456 } for k in ['foo', 'truc', 'bidule']: a.setdefault(k, 'x') |
||||
intersection (2,3) |
array_intersect(array(1,2,3), array(2,3,4)); // fonctionne aussi avec des arrays assoc. |
@a = (1,2,3); @b = (2,3,4); %c = map{$_ => 1} @a; @c = grep($c{$_}, @b); |
set([1,2,3]).intersection(set([2,3,4])) # seulement avec des set (liste d'éléments uniques) |
List<Integer> a = new ArrayList<Integer>(); List<Integer> b = new ArrayList<Integer>(); Integer[] a1 = {1, 2, 3}; Integer[] b1 = {2, 3, 4}; Collections.addAll(a, a1); Collections.addAll(b, b1); a.retainAll(b); |
|
différence symétrique (1,4) |
$a = array(1,2,3); $b = array(2,3,4); $i = array_intersect($a,$b); $d = array_merge(array_diff($a,$i), array_diff($b,$i)); |
@a=(1,2,3); @b = (2,3,4); foreach (@a,@b) { $c{$_}++ } foreach (keys %c) { push(@d, $_) unless $c{$_} > 1 } |
set([1,2,3]).symmetric_difference(set([2,3,4])) | TODO |
TODO |
trier une liste |
$a = array(4, 2, 3, 10); sort($a); // tri numérique |
@a = (4, 2, 3, 10); @a = sort(@a); // tri alphabétique // tri numérique : @a = sort({ $a <=> $b } @a); |
a = [4, 2, 3, 10] b = sorted(a) # tri numérique # a est inchangé a.sort() # a est trié |
a = [4, 2, 3, 10]; a = a.sort(); // tri alphabétique // tri numérique : a.sort(function(x,y) { return x - y; }); |
List<Integer> a = new ArrayList<Integer>(); Integer[] b = {10, 2, 3, 4}; Collections.addAll(a, b); Collections.sort(a); |
avec des accents UTF-8 |
$b = array('a', 'z', 'é', 'b', 'e'); setlocale(LC_COLLATE, 'fr_FR.UTF-8'); sort($b, SORT_LOCALE_STRING); // ou $collator = new Collator('fr_FR'); $collator->sort($b); // voir aussi Collator::asort (mais pas de ksort) |
TODO |
b = ['a', 'z', 'é', 'b', 'e'] import locale locale.setlocale(locale.LC_COLLATE, 'fr_FR.UTF-8') b.sort(cmp = locale.strcoll) |
TODO |
TODO |
comparer deux chaines UTF-8 |
setlocale(LC_COLLATE, 'fr_FR.UTF-8'); echo strcoll('élément', 'zéro'); // pas strcmp ! |
TODO |
import locale locale.setlocale(locale.LC_COLLATE, 'fr_FR.UTF-8') print locale.strcoll('élément', 'zéro') # pas cmp ! |
alert('élément'.localeCompare('zéro')); |
TODO |
max d'une liste |
echo max($a); |
use List::Util qw/max/; print max(@a); |
print max(a) |
alert(Math.max.apply(null, a)); | System.out.println(Collections.max(a)); |
retirer un élément en tête |
echo array_shift($a); # 1 |
print shift(@a); |
print a.pop(0) |
alert(a.shift()); |
System.out.println(a.remove(0)); |
en fin de liste |
echo array_pop($a); # 4 | print pop(@a); | print a.pop() | alert(a.pop()); | System.out.println(a.remove(a.size()-1)); |
ajouter en tête |
array_unshift($a, 5); |
unshift(@a, 5); |
a.insert(0, 5) |
a.unshift(5); |
a.add(0, 5); |
ou ailleurs |
array_splice($a,2,0,9); |
splice(@a,2,0,9); |
a.insert(2,9) |
a.splice(2,0,9); |
a.add(2, 9); |
concaténer deux listes ou hashes |
$c = array_merge($a, $b); // $b écrase $a si clés communes // ou $c = $a + $b; // $a écrase $b si clés communes |
@c = (@a, @b); %c = (%a, %b); |
c = a + b # ou étend a avec b a.extend(b) c = dict(a, **b) # utilise la notion de **kwargs (keyword arguments) |
c = a.concat(b); # hashes avec jQuery c = $.extend({}, a, b); # ou étend a avec b $.extend(a, b) |
List<Integer> c = new ArrayList<Integer>(a); c.addAll(b); |
modifier une liste |
$a = array_map(function($v) { return $v * 2; }, $a); // ou array_walk($a, function(&$v) { $v *= 2; }); // 5.3+ // ou avant PHP 5.3 : function modif(&$v) { $v *= 2; } array_walk($a, "modif"); |
@a = map { $_ * 2 } @a; |
a = [x * 2 for x in a] # ou a = map(lambda x: x * 2, a) |
// à partir de IE9 a = a.map(function(x) { return x * 2; }) // (teste r Array.prototype.map)
|
|
avec un paramètre supplémentaire |
array_walk($a, function(&$v, $k, $p) { $v *= $p; }, 3); |
||||
filtrer une liste (garde les éléments pairs) | $a = array(1,2,3,4); $b = array_filter($a, function($e) { return $e % 2 == 0; }); |
TODO | TODO | a = [1,2,3,4]; b = a.filter(function(e) { return e % 2 == 0; }); |
TODO |
trier un hash par valeur (et non par clé) |
$a = array("tom" => 5, "jerry" => 2, "alfonso" => 3); asort($a); // ou array_multisort(array_values($a), $a); // voir aussi usort, etc. // bref : php.net/manual/fr/array.sorting.php |
%a = ("tom" => 5, "jerry" => 2, "alfonso" => 3); @k = sort { $a{$b} <=> $a{$a} } keys %a; foreach (@k) { $b{$_} = $a{$_}; } %a = %b; undef %b, @k; |
a = { "tom" : 5, "jerry" : 2, "alfonso" : 3 } from operator import itemgetter a = sorted(a.items(), key=itemgetter(1)) |
a = { "tom" : 5, "jerry" : 2, "alfonso" : 3 }; // a est un objet, il n'y a pas d'ordre // mais on peut créer un array d'arrays // qui est ordonné, lui... b = []; for (k in a) { b.push([k, a[k]]); // [clé, valeur] } b.sort(function(x,y) { return x[1] - y[1]; }); console.log(b); |
Map<String, Integer> a = new HashMap<String,
Integer>(); a.put("tom", 5); a.put("jerry", 2); a.put("alfonso", 3); Map<String, Integer> b = new HashMap<String, Integer>(); Iterator<String> i = sortByValue(a).iterator(); while ( i.hasNext() ) { String k = i.next(); b.put(k, a.get(k)); } a.clear(); a.putAll(b); b.clear(); List<String> sortByValue(final Map<String, Integer> map) { List<String> k = new ArrayList<String>(); k.addAll(map.keySet()); Collections.sort(k, new Comparator<String>() { public int compare(String k1, String k2) { Integer v1 = map.get(k1); Integer v2 = map.get(k2); return v2 - v1; } }); return k; } |
trier un hash par clé |
ksort($a); // voir aussi uksort |
TODO |
a = sorted(a.items()) |
TODO |
|
$aref = &$a; |
$aref = \@a; |
# tout est référence |
# tout est référence |
||
# sans équivalent ? |
print ref($aref); # affiche ARRAY(0x1998b08) |
# n/a |
# n/a |
||
echo $aref[1]; # affiche 2 |
print $$aref[1]; # affiche 2 |
# n/a |
# n/a |
||
$a = array('foo', 'bar', 123); foreach ($a as $i => $v) { echo "index $i : valeur $v\n"; } |
TODO |
a = ['foo', 'bar', 123] for i, v in enumerate(a): print "index", i, "valeur", v |
TODO |
||
fonction avec un nombre d'arguments variable | function f() { echo "nbe d'args : ".func_num_args()."\n"; print_r(func_get_args()); } // à partir de PHP 5.6 : function f(...$params) { echo "nbe d'args : ".count($params)."\n"; print_r($params); } f(4, 3, 2, 1); |
TODO | def f(*params): print "nbe d'args :", len(params) print params f(4, 3, 2, 1) |
function f() { console.log("Nbe d'args : " + arguments.length); for (var i=0; i < arguments.length; i++) { console.log(arguments[i]); } } f(4, 3, 2, 1); |
TODO |
passer une liste d'arguments à une fonction ("unpacking", déballer les arguments) |
function f($a, $b, $c) { echo $a + $b + $c; } $a = array(5, 6, 7); // avec PHP 5.6 : f(...$a); // avant 5.6, obligé de faire : f($a[0], $a[1], $a[2]); |
TODO | def f(a, b, c): print a + b + c a = [5, 6, 7] f(*a) |
function f(a, b, c) { console.log(a + b + c); } a = [5, 6, 7]; f.apply(null, a); |
TODO |
fonction lambda (anonyme) |
$f = function($a, $b) { return $a + $b; }; // avant PHP 5.3 : // $f = create_function('$a,$b', 'return $a + $b;'); echo $f(1, 2); |
$f = sub { ($a, $b) = @_; return $a + $b }; print &$f(1,2); |
f = lambda a, b: a + b print f(1,2) |
f = function(a, b) { return a + b; } alert(f(1,2)); |
|
particularité PHP 5.3+ |
$a = array(0,1,2,3,4,5,6,7,8,9); foreach (array(2,3,4) as $d) { $b = array_filter($a, function($v) use($d) { return !($v % $d); }); print_r($b); } |
||||
particularité Javascript | // exécution immédiate d'une fonction anonyme (function() { var a = 'coucou'; alert(a); })(); // ou (moins explicite) !function() { var a = 'bonjour'; alert(a); }(); // le ! provoque l'évaluation de ce qui suit |
||||
modifier une liste dans une fonction (dans cet exemple, remplacer
tout le contenu de la liste, pour que ce soit plus parlant) |
function change(&$a) { $a = array(5, 6); } change($a); print_r($a); |
sub change { $a = shift(@_); @$a = (5, 6); } change(\@a); print join(",",@a); |
def change(a): # a = [5, 6] # erreur ! # a resterait [1, 2, 3, 4] del a[:] a = [5, 6] change(a) print a |
static void Change(List<Integer> a) { Integer[] b = {5, 6}; // a = new ArrayList<Integer>(Arrays.asList(b)); // erreur ! // a resterait [1, 2, 3, 4] a.clear(); a.addAll(Arrays.asList(b)); } Change(a); System.out.println(a.toString()); |
|
même chose en ajout |
function change(&$a) { $a[] = 5; $a[] = 6; // ou : array_push($a, 7); } change($a); print_r($a); |
sub change { $a = shift(@_); push @$a, (5, 6, 7); } change(\@a); print join(",",@a); |
def change(a): a.extend([5, 6, 7]) change(a) print a |
static void Change(List<Integer> a) { Integer[] b = {5, 6, 7}; a.addAll(Arrays.asList(b)); } Change(a); System.out.println(a.toString()); |
|
eval('print join("+", $a);'); # ne pas oublier le point-virgule |
eval('print join("+", @a)'); |
print eval('"+".join(a)') # mais pas eval('print "+".join(a)') Syntax error |
// sans équivalent |
||
variable globale |
$a = 1; function b() { global $a; echo $a; # OK $a = 2; } function c() { echo $a; # "Undefined variable" } b(); # affiche 1 echo $a; # affiche 2 |
$a = 1; sub b { print $a; $a = 2; } b(); # affiche 1 print $a; # affiche 2 # note : voir aussi our() (avec un package) |
a = 1 def b(): global a # inutile pour juste lire a print a a = 2 b() # affiche 1 print a # affiche 2 |
a = 1; // ou var a = 1; function b() { alert(a); a = 2; } b(); // affiche 1 alert(a); // affiche 2 // ici, a est en fait window.a // et si on ne l'avait pas créée par a = 1 // on l'aurait créée globale dans la fonction ! // (dangereux, interdit en mode strict) |
// pas de concept de variable "globale" // mais variable "de classe" : class Essai { public static int a = 1; } // on y accède par Essai.a |
variable locale |
$a = 1; function b() { $a = 2; echo $a; } function c($a) { echo $a; }
c(3); # affiche 3b(); # affiche 2 echo $a; # affiche 1 |
$a = 1; # ou my $a = 1; sub b { my $a = 2; # ou local $a = 2; print $a; } sub c { my $a = shift; print $a; } c(3); # affiche 3 b(); # affiche 2 print $a; # affiche 1 # note 1 : voir local vs my # note 2 : my $a est un mauvais exemple... # voir man perlvar à propos de sort() |
a = 1 def b(): a = 2 print a def c(a): print a c(3) # affiche 3 b() # affiche 2 print a # affiche 1 |
a = 1; // ou var a = 1; function b() { var a = 2; alert(a); } function c(a) { alert(a); } c(3); // affiche 3 b(); // affiche 2 alert(a); // affiche 1 |
class Essai { void b() { int a = 2; System.out.println(a); } void c(int a) { System.out.println(a); } } // ... Essai obj = new Essai(); int a = 1; obj.c(3); // affiche 3 obj.b(); // affiche 2 System.out.println(a); // affiche 1 |
déréférencer une liste en retour d'une fonction (exemple) |
$a = "foo-bar"; // à partir de PHP 5.4 : echo explode('-', $a)[0]; // PHP 5.3 echo current(explode('-', $a)); // foo |
TODO |
a = 'foo-bar' print a.split('-')[0] |
a = "foo-bar"; alert(a.split('-')[0]); |
TODO |
constante |
define("FOO", 42); echo FOO; // ou echo constant("FOO"); // dans une classe A const FOO = 42; echo self::FOO; // dans la classe echo A::FOO; // ailleurs |
use constant FOO => 42; |
# n'existe pas. # créer une classe avec un __setattr__ ad hoc, # cf. article d'Alex Martelli "Constants in python" |
# n'existe pas |
public static final int FOO = 42; |
vérifier si une fonction existe | if (function_exists('a')) { a(); } |
if (defined &a) { a(); } |
if 'a' in locals() and hasattr(a, '__call__'): a() |
if (this.window['a'] && typeof(this.window['a'] ===
'function')) { a(); } // ou, par exemple, pour savoir si la // fonction indexOf existe pour les tableaux : if ('indexOf' in Array.prototype) { alert("foobar".indexOf("b")); } // ou encore : if (Array.prototype.indexOf) { alert("foobar".indexOf("b")); } |
|
appeler une fonction par son nom |
function a($a) { echo "ici ".__FUNCTION__."($a)\n"; } $b = 'a'; call_user_func($b, 'foo'); call_user_func_array($b, array('foo')); $b('foo'); |
TODO |
# si la fonction est dans un module truc.py : def a(a): print 'ici a(' + a + ')' # utilisation : import truc b = 'a'; getattr(truc, b)('foo') |
function a() { alert('ici ' + arguments.callee.name); } b = 'a'; window[b](); // car appeler a() revient à appeler window['a']() |
|
type des paramètres (type hinting) |
function a(UneClasse $x) // PHP 5 function b(array $x) // PHP 5.1 function c(callable $x) // PHP 5.4 // et dans ce cas on peut faire : $x("foo"); |
TODO (seulement le nombre, pas le type ?) |
# pas pareil, mais utile dans un IDE def a(x): """ @x: int """ print x + 1 |
||
function a() { echo "ici ".__FUNCTION__."\n"; echo "ligne ".__LINE__."\n"; echo "fichier ".__FILE__."\n"; echo "répertoire ".__DIR__."\n"; } # avant PHP 5.3 __DIR__ n'existait pas # => dirname(__FILE__) |
TODO |
import inspect def a(): print "ici", inspect.stack()[0][3] print "ligne", inspect.stack()[0][2] |
function a() { alert('ici ' + arguments.callee.name); // ou afficher la déclaration de a : alert('ici ' + arguments.callee); } |
||
nom de la fonction appelante | function a() { list (,$a) = debug_backtrace(); echo "appel par ".$a['function']; if (isset($a['class'])) echo " dans ".$a['class']; } function b() { a(); } b(); // affiche "appel par b" |
function a() { alert('appel par ' + arguments.callee.caller.name); // ou la déclaration de l'appelant : alert('appel par ' + arguments.callee.caller); } function b() { a(); } b(); // affiche "appel par b" |
|||
try { $dbh = new PDO('mysql:host=localhost;dbname=test', 'u', 'p'); $sth = $dbh->query("create table if not ..."); # ... # non ! $a = $dbh->quote($a); $sth = $dbh->prepare("select...where a=?"); $sth->execute(array($a)); echo $sth->rowCount()."\n"; while($row = $sth->fetch()) { echo $row[0]; } # ou : # while($row = $sth->fetch(PDO::FETCH_ASSOC)) { # echo $row["a"]; # } # ou $rows = $sth->fetchAll(); } catch (PDOException $e) { echo "Erreur : ".$e->getMessage(); } |
use DBI; use DBD::mysql; $dbh = DBI->connect("dbi:mysql:test:localhost", "u", "p"); $dbh->do("create table if not exists test ..."); # ... # non ! $a = $dbh->quote($a); $sth = $dbh->prepare("select ... where a=? and b=?"); $sth->execute($a,$b); print $sth->rows, "\n"; while(@row = $sth->fetchrow_array) { print $row[0]; } # ou # while($row = $sth->fetchrow_hashref) { # print $row->{"a"}; # } # ou $rowsref = $sth->fetchall_arrayref; |
import MySQLdb as db try: dbh = db.connect('localhost','u','p','test', charset="utf8", use_unicode=True) c = dbh.cursor() # ou dbh.cursor(db.cursors.DictCursor) c.execute('create table if not exists t (a int, b text)') q = 'insert into t values (%s, %s)' c.execute(q, (10, 'hé !')) dbh.commit() c.execute('select * from t') print c.rowcount for row in c: print row # ou print row["a"] si DictCursor # ou rows = c.fetchall() except db.Error, e: print "Erreur :", e.args[0], e.args[1] |
try { Class.forName("com.mysql.jdbc.Driver"); java.sql.Connection db = DriverManager.getConnection("jdbc:mysql://localhost/test", "u", "p"); Statement st = db.createStatement(); System.out.println(st.execute("create table if not exists test (x int)")); // ... PreparedStatement pst = db.prepareStatement("select * from test where a=? and b=?"); pst.setString(1, a); pst.setLong(2, b); ResultSet res = pst.executeQuery(); // pas de méthode directe pour le rowcount while (res.next()) { System.out.println(res.getString(1)); System.out.println(res.getString("a")); } } catch (SQLException e) { System.out.println("Erreur : " + e.getErrorCode() + " " + e.getMessage()); } |
||
pour attraper les warnings |
import warnings warnings.filterwarnings('error', category=db.Warning) # ... except db.Warning, e: print 'Warning :', e.args |
||||
import sqlite3 as db try: dbh = db.connect('fichier.sqlite') dbh.text_factory = str # pour utf8 c = dbh.cursor() c.execute('create table if not exists t (a varchar(10))') q = 'insert into t values (?)' c.execute(q, ('hé !',)) q = 'select * from t where a like ?' c.execute(q, ('h%',)) for row in c: print row[0] except db.Error, e: print "Erreur :", e.args[0], e.args[1] |
|||||
last insert id |
cur.execute('insert ...') print cur.lastrowid # ou print dbh.insert_id() dbh.commit() |
||||
attraper les warnings |
import warnings warnings.simplefilter('error', mdb.Warning) try: cur.execute('insert ...') except mdb.Error, e: print 'Erreur', e except mdb.Warning, e: print 'Warning', e |
||||
idem mais localement |
import warnings with warnings.catch_warnings(): warnings.simplefilter('error', mdb.Warning) try: cur.execute('insert ...') except mdb.Error, e: print 'Erreur 1', e except mdb.Warning, e: print 'Warning 1', e # ici c'est fini, on ne les attrape plus try: cur.execute('insert ...') except mdb.Error, e: print 'Erreur 2', e except mdb.Warning, e: print 'Warning 2', e |
||||
note Java : CLASSPATH courant ? |
for (URL url:
((URLClassLoader)ClassLoader.getSystemClassLoader())
.getURLs()) { System.out.println(url.getFile()); } |
||||
particularité Python |
for i in range(10): print '10 /', i, '=', try: print 10 / i, except ZeroDivisionError: print "division par zéro" else: print "tout va bien" |
||||
c'est différent de try ... finally |
for i in range(10): print '10 /', i, '=', try: print 10 / i, except ZeroDivisionError: print "division par zéro", finally: print '[terminé]' |
for (int i=0; i<10; i++) { System.out.print("10 / " + i + " = "); try { System.out.print(10 /i); } catch (ArithmeticException e) { System.out.print("division par zéro"); } finally { System.out.println(" [terminé]"); } } |
|||
on peut combiner les deux |
for i in range(10): print '10 /', i, '=', try: print 10 / i, except ZeroDivisionError: print "division par zéro", else: print "tout va bien", finally: print '[terminé]' |
||||
objet |
class A { function __construct($a1, $a2, $a3, $a4) { $this->a1 = $a1; $this->a2 = $a2; $this->a3 = $a3; $this->a4 = $a4; } function somme() { return $this->a1 + $this->a2 + $this->a3 + $this->a4; } } $a = new A(1, 2, "foo", "bar"); echo $a->somme(); // 3 |
package A; sub new { my $class = shift; my $self = { a1 => shift, a2 => shift, a3 => shift, a4 => shift }; bless ($self, $class); return $self; } sub somme { my ($self) = @_; return $self->{a1} + $self->{a2} + $self->{a3} + $self->{a4}; } $a = new A(1, 2, "foo", "bar"); # ou $a = A->new(1, 2, "foo", "bar"); print $a->somme(); # 3 |
class A: def __init__(self, a1, a2, a3, a4): self.a1 = a1 self.a2 = a2 self.a3 = a3 self.a4 = a4 def somme(self): return self.a1 + self.a2 + self.a3 + self.a4 a = A(1, 2, "foo", "bar") print a.somme() # TypeError: unsupported operand type(s) for +: 'int' and 'str' |
function A(a1,a2,a3,a4) { this.a1 = a1; this.a2 = a2; this.a3 = a3; this.a4 = a4; // cette méthode serait dupliquée // dans chaque instance : /* this.somme = function() { return this.a1 + this.a2 + this.a3 + this.a4; }; */ } // mieux : A.prototype.somme = function() { return this.a1 + this.a2 + this.a3 + this.a4; }; a = new A(1,2,"foo","bar"); console.log(a.somme()); // 3foobar |
class A { int a1; int a2; String a3; String a4; A(int a1, int a2, String a3, String a4) { this.a1 = a1; this.a2 = a2; this.a3 = a3; this.a4 = a4; } int somme() { return this.a1 + this.a2; // impossible ne compile pas // + this.a3 // + this.a4; } } A a = new A(1, 2, "foo", "bar"); System.out.println(a.somme()); // 3 |
echo $a->a4; |
print $a->{a4}; |
print a.a4 |
alert(a.a4); alert(a["a4"]); |
System.out.println(a.a4); |
|
version « Perl moderne » | package A { use Moose; has 'a1' => (is => 'rw', isa => 'Int'); has 'a2' => (is => 'rw', isa => 'Int'); has 'a3' => (is => 'rw', isa => 'Str'); has 'a4' => (is => 'rw', isa => 'Str'); } my $a = A->new(a1 => 1, a2 => 2, a3 => "foo", a4 => "bar"); print $a->a3(); |
||||
echo get_class($a); |
print ref($a); |
print a.__class__.__name__ |
alert(a.constructor.name); |
System.out.println(a.getClass().getSimpleName()); |
|
if (is_a($a, 'A')) { echo '$a est un A'; } // ou if ($a instanceof A) { echo '$a est un A'; } |
TODO |
if isinstance(a, A): print "a est un A" |
if (a instanceof A) { alert("a est un A"); } |
if (a instanceof A) { System.out.println("a est un A"); } |
|
print_r(get_object_vars($a)); // ou $r = new ReflectionObject($a); print_r($r->getProperties()); |
|||||
accès à une variable privée |
// class A { private $a1; ... $p = $r->getProperties(); $p[0]->setAccessible(true); print $p[0]->getValue($a); |
||||
accès par le nom de l'attribut |
if (property_exists($a, "a1")) { $attr = "a1"; $a->$attr = "blah"; echo $a->$attr; } |
TODO |
if hasattr(a, 'a1'): setattr(a, 'a1', 'blah') print getattr(a, 'a1') |
if (a.hasOwnProperty('a1')) { a['a1'] = 'blah'; alert(a['a1']); } // normalement supporté par tout navigateur. // vérifier que le navigateur a cette méthode : // if (Object.prototype.hasOwnProperty) { ... |
if (a.getClass().getField("a1") != null) { Field f = a.getClass().getField("a1"); f.set(a, "blah"); System.out.println(f.get(a)); } // nécessite un import java.lang.reflect.Field; // et peut lancer tout un tas d'exception... |
surcharge |
class A { function __construct($a1, $a2, $a3, $a4) { $this->a1 = $a1; $this->a2 = $a2; $this->a3 = $a3; $this->a4 = $a4; } function __toString() { return(join(" + ", array($this->a1, $this->a2, $this->a3, $this->a4))); } } $a = new A(1, 2, "foo", "bar"); echo $a; |
package A; sub new { my $class = shift; my $self = { a1 => shift, a2 => shift, a3 => shift, a4 => shift }; bless ($self, $class); return $self; } use overload ('""' => 'to_string'); sub to_string { my ($this) = @_; return join(" + ", ($this->{a1}, $this->{a2}, $this->{a3}, $this->{a4})); } $a = new A(1, 2, "foo", "bar"); print $a; |
class A: def __init__(self, a1, a2, a3, a4): self.a1 = a1 self.a2 = a2 self.a3 = a3 self.a4 = a4 def __repr__(self): return " + ".join([str(self.a1), str(self.a2), str(self.a3), str(self.a4)]) a = A(1, 2, "foo", "bar") print a |
function A(a1,a2,a3,a4) { this.a1 = a1; this.a2 = a2; this.a3 = a3; this.a4 = a4; } A.prototype.toString = function() { return [this.a1, this.a2, this.a3, this.a4].join(" + "); } a = new A(1,2,"foo","bar"); alert(a); |
class A { int a1; int a2; String a3; String a4; A(int a1, int a2, String a3, String a4) { this.a1 = a1; this.a2 = a2; this.a3 = a3; this.a4 = a4; } @Override public String toString() { return a1 + " + " + a2 + " + " + a3 + " + " + a4; } } A a = new A(1, 2, "foo", "bar"); System.out.println(a); |
héritage |
class B extends A { function __construct($a1, $a2, $a3, $a4) { parent::__construct($a1, $a2, $a3, $a4); } function bonjour() { return("bonjour".$this->a1); } } $b = new B(1,2,3,4); echo $b->bonjour(); echo $b; // appelle __toString() de A |
TODO |
class B(A): def bonjour(self): return "bonjour" + str(self.a1) b = B(1,2,3,4) print b.bonjour() print b # appelle __repr__ de A |
function B() { A.apply(this, arguments); } B.prototype = new A(); B.prototype.constructor = B; B.prototype.bonjour = function() { return "bonjour" + this.a1; } b = new B(1,2,3,4); alert(b.bonjour()); alert(b); |
class B extends A { B(int a1, int a2, int a3, int a4) { super(a1, a2, String.valueOf(a3), String.valueOf(a4)); } public String bonjour() { return "bonjour" + a1; } } B b = new B(1,2,3,4); System.out.println(b.bonjour()); System.out.println(b); |
trier une liste d'objets | $l = array( new A(3,4,'c','d'), new A(1,2,'a','b'), ); usort($l, function($a, $b) { if ($a->a1 == $b->a1) return 0; return ($a->a1 > $b->a1) ? 1 : -1; }); |
TODO |
l = [ A(3,4,'c','d'), A(1,2,'a','b') ] l.sort(key = lambda a: a.a1) # l.sort(key = lambda a: a.a1, reverse = False) |
TODO |
TODO |
idem sur chaîne UTF-8 |
$l = array( new A(3,4,'z','z'), new A(1,2,'é','é'), ); setlocale(LC_COLLATE, 'fr_FR.UTF-8'); usort($l, function($a, $b) { return strcoll($a->a3, $b->a3); }); |
TODO |
TODO |
TODO |
TODO |
accès par le nom de la méthode |
if (method_exists($b, "bonjour")) { $meth = "bonjour"; echo $b->$meth(); } |
TODO |
methode = getattr(b, 'bonjour') methode() |
TODO |
TODO |
introspection |
$r = new ReflectionClass('B'); foreach ($r->getMethods() as $m) { echo $m->getName()."\n"; } |
TODO |
TODO |
TODO |
TODO |
trait (réutilise du code horizontal, ici la méthode coucou) (ou contourne l'asbence d'héritage multiple) |
// à partir de PHP 5.4 trait A { function coucou() { echo "coucou ".$this->z; } } class B { use A; private $z = 1; } class C { use A; private $z = 2; } $b = new B(); $b->coucou(); $c = new C(); $c->coucou(); |
||||
idem sans trait, par héritage |
// PHP < 5.4 class A { protected $a; function coucou() { echo "coucou ".$this->a; } } class B extends A { function __construct() { $this->a = 1; } } class C extends A { function __construct() { $this->a = 2; } } $b = new B(); $b->coucou(); $c = new C(); $c->coucou(); |
||||
idem sans trait, par une classe utilitaire |
class A { static function coucou($a) { echo "coucou $a"; } } class B { function coucou() { A::coucou(1); } } class C { function coucou() { A::coucou(2); } } $b = new B(); $b->coucou(); $c = new C(); $c->coucou(); |
||||
objet anonyme | $a = new stdClass; $a->truc = 'valeur'; // ou par conversion de tableau en objet : $a = (object) array('truc' => 'valeur'); |
TODO | ? | a = { "truc": "valeur" }; | ? |
interface |
TODO |
||||
espaces de noms |
# à partir de PHP 5.3 # dans ma_lib.php : namespace ma\librairie\salutations; function coucou() { echo "coucou !\n"; } # utilisation : require 'ma_lib.php'; ma\librairie\salutations\coucou(); |
||||
alias |
require 'ma_lib.php'; use ma\librairie\salutations as a; a\coucou(); |
||||
conversion objet en array |
$a = new A(1,2,3,4); $aa = (array) $a; // ou json_decode(json_encode($a), true); |
// solution partielle // ne gère pas plusieurs dimensions : a = A(1,2,3,4) aa = dict((k, v) for k, v in a.__dict__.iteritems()) |
// inutile : on peut écrire a["a1"] ou a.a1 for (x in a) { if (typeof(a[x] != "function") { alert(a[x]); } } |
||
et l'inverse |
$o = (object) array('foo' => 123, 'bar' => 456); echo $o->foo; |
||||
l'heure courante |
echo date("H:i:s"); |
use POSIX qw(strftime); print strftime "%H:%M:%S", localtime; # ou @now = localtime; # ou localtime(); printf("%02d:%02d:%02d\n", $now[2], $now[1], $now[0]); # ou plus moderne : use Time::Piece; $now = localtime; print $now->hms; |
from datetime import datetime print datetime.now().strftime("%H:%M:%S") # ou from time import localtime, strftime print strftime("%H:%M:%S", localtime()) |
a = new Date(); alert(a.toLocaleTimeString()); |
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new
Date())); |
secondes depuis le 01/01/1970 | echo time(); | print time(); | from time import time print time() # donne des décimales (que print tronque) |
a = new Date(); alert(parseInt(a / 1000)); alert(Math.round(a / 1000)); |
System.out.println(System.currentTimeMillis() / 1000L); // 1000L pour éviter une conversion implicite // de 1000 en objet Long // (détail pour les performances) |
timestamp horodatage AAAA-MM-JJ HH:MM:SS |
// date locale : echo date("Y-m-d H:i:s"); // GMT (UTC) sans timezone : echo gmdate("Y-m-d H:i:s"); |
use Time::Piece; $now = localtime; print $now->ymd." ".$now->hms; |
from datetime import datetime print datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
a = new Date(); // date locale : alert( a.getFullYear() + '-' + ('00' + (a.getMonth()+1)).slice(-2) + '-' + ('00' + a.getDate()).slice(-2) + ' ' + ('00' + a.getHours()).slice(-2) + ':' + ('00' + a.getMinutes()).slice(-2) + ':' + ('00' + a.getSeconds()).slice(-2) ); // GMT (UTC) sans timezone : alert( a.getUTCFullYear() + '-' + ('00' + (a.getUTCMonth()+1)).slice(-2) + '-' + ('00' + a.getUTCDate()).slice(-2) + ' ' + ('00' + a.getUTCHours()).slice(-2) + ':' + ('00' + a.getUTCMinutes()).slice(-2) + ':' + ('00' + a.getUTCSeconds()).slice(-2) ); // plus simple avec Moment.js a = moment(); alert(a.format('YYYY-MM-DD HH:mm:ss')); |
System.out.println(new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss").format(new Date())); |
convertir une date dans une autre zone | $utc = new DateTimeZone("UTC"); $paris = new DateTimeZone("Europe/Paris"); $a = new DateTime("2013-08-07 12:34:56", $utc); $a->setTimezone($paris); echo $a->format('Y-m-d H:i:s'); |
TODO | TODO | // utiliser Moment.js a = moment.tz("2013-08-07 12:34:56", "UTC"); a.tz("Europe/Paris"); alert(a.format('YYYY-MM-DD HH:mm:ss')); |
TODO |
date locale "lundi 21 juillet 1969" |
setlocale(LC_TIME, "fr_FR.UTF-8"); $a = mktime(0,0,0,7,21,1969); echo strftime("%A %e %B %Y", $a); |
import locale locale.setlocale(locale.LC_TIME, 'fr_FR.UTF-8') from datetime import datetime a = datetime(1969,7,21) print a.strftime("%A %e %B %Y") |
// le plus approchant a = new Date(1969,6,21,0,0,0); alert(a.toLocaleString()); // ou utiliser une librairie qui émule strftime |
Calendar a = GregorianCalendar.getInstance(); a.set(1969,6,21,0,0,0); // attention au mois System.out.println(new SimpleDateFormat("EEEE d MMMM yyyy").format(a.getTime())); |
|
retrouver le jour de la semaine | echo date('N', $a); // 1 = lundi (ISO-8601) |
TODO | TODO | alert(a.getDay()); // 1 = lundi |
TODO |
ajouter 14 jours à cette date = lundi 4 août 1969 |
echo strftime("%A %e %B %Y", strtotime('+14 days', $a)); // notes sur DateTime : $b = new DateTime(strftime("%F",$a)); $b->add(new DateInterval('P14D')); echo $b->format('l j F Y'); // KO pas de locale ! // donc obligé de faire : echo strftime("%A %e %B %Y", $b->getTimestamp()); |
from datetime import datetime, timedelta print (a + timedelta(14)).strftime("%A %e %B %Y") |
a.setDate(a.getDate() + 14); |
a.add(Calendar.DAY_OF_MONTH, 14); |
|
nombre de jours entre deux dates : 24 et 31 octobre 2013
(changement d'heure) |
$a = mktime(0,0,0,10,24,2013); $b = mktime(0,0,0,10,31,2013); echo round(($a - $b)/86400); |
from datetime import date # ou datetime... a = date(2013,10,24) b = date(2013,10,31) print (a - b).days |
a = new Date(2013,9,24,0,0,0); b = new Date(2013,9,31,0,0,0); alert(Math.round((a - b)/86400000)); // attention, milli-secondes ! |
||
comparer deux dates |
if ($a < $b) |
if a < b: |
if (a < b) |
||
convertir une chaine de date en timestamp |
echo strtotime('2012-12-20'); // ok echo strtotime('20/12/2012'); // ko, rien ! // avec DateTime : $a = DateTime::createFromFormat( 'd/m/Y H:i:s', '20/12/2012 00:00:00' ); echo $a->format('U'); // avec le fuseau horaire de l'Alaska : $a = DateTime::createFromFormat( 'd/m/Y H:i:s', '20/12/2012 00:00:00', new DateTimeZone('America/Anchorage') ); echo $a->format('U'); |
from dateutil.parser import parse print parse('20/12/2012').strftime('%s') |
alert(Date.parse("Dec 20, 2012")); // attention, milli-secondes ! // avec le fuseau horaire de l'Alaska : alert(Date.parse("2012-12-20T00:00:00.000-09:00")); // avec le datepicker de jQuery : alert($.datepicker .parseDate("dd/mm/yy", "20/12/2012") .getTime()); // ou avec Moment.js : a = moment("20/12/2012", "DD/MM/YYYY"); alert(a.format('X')); // millisecondes : alert(a.format('x')); |
||
"découper" une date |
print_r(strptime("31/10/2013", "%d/%m/%Y")); |
from time import strptime print strptime("31/10/2013", "%d/%m/%Y") |
|||
cloner un objet Date |
b = new Date(a); |
Calendar b = (Calendar) a.clone(); |
|||
lancer un sous-processus |
print shell_exec("whois linux.com"); |
print `whois linux.com`; |
import os print os.popen("whois linux.com").read() |
Process p = Runtime.getRuntime().exec("whois linux.com"); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); String l; while ((l = r.readLine()) != null) { System.out.println(l); } r.close(); |
|
limiter le temps d'excécution d'une opération, par exemple la
connexion à un port caché par un firewall (22 = SSH) |
// ne fonctionne qu'en ligne de commande declare(ticks=1); function signal_handler($signal) { print "timeout atteint\n"; pcntl_alarm(1); } pcntl_signal(SIGALRM, "signal_handler", true); pcntl_alarm(1); $f = fsockopen("herverenault.fr", 22, $errno, $errstr, 30); if ($f) { echo "réponse du serveur : "; echo fgets($f, 4096); } else { echo "connexion impossible en moins de 3 s\n"; } |
use Socket; $a = sockaddr_in(22, inet_aton('herverenault.fr')); socket(S, PF_INET, SOCK_STREAM, getprotobyname('tcp')); eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm 3; connect(S, $a); alarm 0; }; if ($@) { print "connexion impossible en moins de 3 s\n"; } else { $ligne = <S>; print "réponse du serveur : $ligne"; } |
import socket, signal s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def handler(n, f): print "timeout atteint" # ou simplement : pass signal.signal(signal.SIGALRM, handler) signal.alarm(3) try: s.connect(('herverenault.fr', 22)) print "réponse du serveur :", s.recv(4096) except: print "connexion impossible en moins de 3 s" |
TODO |
|
résolution DNS (DNS lookup) |
echo gethostbyname("herverenault.fr"); |
$a = gethostbyname("herverenault.fr"); print inet_ntoa($a); # scalar obligatoire |
print socket.gethostbyname("herverenault.fr") |
System.out.println(InetAddress .getByName("herverenault.fr") .getHostAddress()); |
|
résolution DNS inverse (DNS reverse lookup) |
echo gethostbyaddr("92.243.27.61"); |
$a = inet_aton("92.243.27.61"); print gethostbyaddr($a, AF_INET); |
print socket.gethostbyaddr("92.243.27.61")[0] |
System.out.println(InetAddress.getByAddress(new byte[] {(byte) 92, (byte) 243, (byte) 27, (byte) 61}).getCanonicalHostName()); | |
récupérer un document par http(s) |
$html =
file_get_contents('https://market.android.com/details?id=fr.herverenault.directdictaphone'); |
use LWP::Simple; $html = get "https://market.android.com/details?id=fr.herverenault.directdictaphone"; |
import urllib2 html = urllib2.urlopen('https://market.android.com/details?id=fr.herverenault.directdictaphone').read() |
StringBuilder html = new StringBuilder(); String line; BufferedReader br = new BufferedReader(new InputStreamReader(new URL("https://market.android.com/details?id=fr.herverenault.directdictaphone") .openStream())); while ((line = br.readLine()) != null) { html.append(line); } // ou avec les HTTPComponents d'Apache : StringBuilder html = new StringBuilder(); String line; HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(new HttpGet("https://market.android.com/details?id=fr.herverenault.directdictaphone")); BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while ((line = br.readLine()) != null) { html.append(line); } |
|
print urlencode("hé"); | use URI::Escape; print uri_escape("hé"); |
import urllib2 print urllib2.quote("hé") |
alert(encodeURIComponent("hé")); // pas escape() obsolète ! // encodeURI() pour une URL complète |
System.out.println(URLEncoder.encode("hé", "UTF-8")); | |
encoder du texte en entités html |
echo htmlentities("hé -> &'", null, "UTF-8"); // encode aussi les accents // ou echo mb_convert_encoding("hé -> &'", "HTML-ENTITIES", "UTF-8"); // mais ça n'encode pas & |
use HTML::Entities; print encode_entities("hé -> &", "&<>"); # ça n'encode pas les accents en UTF-8 |
import cgi print cgi.escape(u"hé -> &'") # encode & mais pas les accents # note Python 3.2+ : html.escape # pour les accents : print u"hé -> &'".encode('ascii', 'xmlcharrefreplace') |
// n'existe pas en JS pur // mais avec jQuery : alert($('<p/>').text("hé -> &'").html()); |
TODO |
vérifier qu'une adresse e-mail est valide | if (filter_var('toto@exemple.fr',FILTER_VALIDATE_EMAIL)) { echo "valide"; } |
TODO | TODO | // utiliser une regex | TODO |
envoyer un mail "old school" |
mail('you@you.com', 'test', 'ok...', 'From: me@me.com'); # ou carrément : $h = popen("/usr/lib/sendmail -t", 'w'); fwrite($h, "From: me@me.com To: you@you.com Subject: test ok..."); pclose($h); |
open H, "| /usr/lib/sendmail -t "; print H 'From: me@me.com To: you@you.com Subject: test ok...'; close H; |
import os h = os.popen("/usr/lib/sendmail -t", "w") h.write('''From: me@me.com To: you@you.com Subject: test ok...''') h.close() |
Process p = Runtime.getRuntime().exec("/usr/lib/sendmail -t"); PrintWriter pw = new PrintWriter(p.getOutputStream()); pw.print("From: me@me.com\n" + "To: you@you.com\n" + "Subject: test\n" + "\n" + "ok...\n"); pw.close(); |
|
envoyer un mail "moderne" avec une partie HTML avec un charset UTF-8, encodée en Quoted-Printable et une partie image encodée en Base64 |
# avec PEAR, sur Ubuntu : # sudo apt-get install php-mail php-mail-mime include "Mail.php"; include "Mail/mime.php"; $mime = new Mail_mime(); $mime->setHTMLBody("<b>hé !</b>"); $mime->addAttachment("image.jpg", "image/jpeg"); $body = $mime->get(array("html_charset" => "UTF-8")); $body = $mime->get(); $headers = $mime->headers(array( "From" => "Moi-même <me@me.com>", "To" => "you@you.com", "Subject" => "Hé, test php !")); $mail = Mail::factory("smtp", array("host" => "localhost")); $mail->send("you@you.com", $headers, $body); # ou mieux, avec SwiftMailer : # ============================ # composer require swiftmailer/swiftmailer require_once 'lib/swift_required.php'; $t = Swift_SmtpTransport::newInstance('localhost', 25); $mailer = Swift_Mailer::newInstance($t); $message = Swift_Message::newInstance('Hé, test php !') ->setFrom(array('me@me.com' => 'Moi-même')) ->setTo('you@you.com') ->setBody('<b>hé !</b> en HTML', 'text/html') ->addPart('hé ! en texte', 'text/plain') ->attach(Swift_Attachment::fromPath('image.jpg')); $result = $mailer->send($message); |
use MIME::Lite; $msg = MIME::Lite->new( From =>'me@me.com', To =>'you@you.com', Subject =>'test perl', Type =>'multipart/mixed'); $part = MIME::Lite->new( Type => 'text/html', Data => '<b>hé !</b>'); $part->attr('content-type.charset' => 'UTF-8'); $msg->attach($part); $msg->attach( Type =>'image/jpeg', Path =>'image.jpg', Filename =>'image.jpg', Disposition => 'attachment'); MIME::Lite->send('smtp', 'localhost'); $msg->send; |
# -*- encoding: UTF-8 -*- import smtplib from email.mime.multipart import MIMEMultipart msg = MIMEMultipart() msg['From'] = 'me@me.com' msg['To'] = 'you@you.com' msg['Subject'] = 'test python' from email.mime.text import MIMEText from email import charset charset.CHARSETS['utf-8'] = (charset.QP, charset.QP, 'utf-8') txt = MIMEText('<b>hé !</b>', 'html', 'UTF-8') msg.attach(txt) from email.mime.image import MIMEImage f = open('image.jpg','rb') img = MIMEImage(f.read()) f.close() msg.attach(img) s = smtplib.SMTP('localhost') s.sendmail('me@me.com', 'you@you.com', msg.as_string()) |
// installer une implémentation de JavaMail, par ex. // http://www.gnu.org/software/classpathx/javamail/javamail.html Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); props.put("mail.from", "me@me.com"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("me@me.com")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("you@you.com")); msg.setSubject("test java"); Multipart mp = new MimeMultipart(); BodyPart p1 = new MimeBodyPart(); p1.setContent("<b>hé !</b>", "text/html; charset=UTF-8"); mp.addBodyPart(p1); BodyPart p2 = new MimeBodyPart(); FileDataSource fds = new FileDataSource("image.jpg"); p2.setDataHandler(new DataHandler(fds)); p2.setFileName(fds.getName()); p2.setFileName("image.jpg"); mp.addBodyPart(p2); msg.setContent(mp); Transport.send(msg); |
|
attention à l'accent ! | echo base64_encode("Hé ho !"); echo base64_decode("SMOpIGhvICE="); |
use MIME::Base64; print encode_base64("Hé ho !"); print decode_base64("SMOpIGhvICE="); |
import
base64 print base64.b64encode("Hé ho !") print base64.b64decode("SMOpIGhvICE=") |
alert(btoa("Hé ho !")); alert(atob("SOkgaG8gIQ==")); |
TODO |
dernière erreur | print_r(error_get_last()); | print "$!\n"; | # inutile, utilise un mécanisme d'exceptions | // utiliser window.onerror | // inutile, utilise un mécanisme d'exceptions |
gestion des erreurs (principe général) | try { foobar(3); foobar(0); foobar(4); } catch (Exception $e) { echo 'Erreur ', $e->getMessage(), "\n"; } // si foobar n'existe pas : // PHP Fatal error: Call to undefined function foobar() // en PHP, une erreur fatale n'est pas une exception // exemple de foobar : function foobar($a) { if ($a == 0) { throw new Exception('division par zéro'); } echo (12 / $a)."\n"; } // affiche : 4 Erreur division par zéro |
TODO | try: foobar(4) foobar(0) foobar(4) except Exception, e: print "Erreur", e # si foobar n'existe pas : # Erreur name 'foobar' is not defined # exemple de foobar : def foobar(a): if a == 0: raise Error('division par zéro') print 12 / a # affiche : 3 Erreur global name 'Error' is not defined |
try { foobar(3); foobar(0); foobar(4); } catch (e) { alert('Erreur ' + e.message); } // si foobar n'existe pas : // Erreur foobar is not defined // exemple de foobar : function foobar(a) { if (a == 0) { throw Error('division par zéro'); } alert(12 / a); } // affiche : 4 Erreur division par zéro |
try { foobar(3); foobar(0); foobar(4); } catch (Exception e) { System.out.println("Erreur " + e.getMessage()); } // si foobar n'existe pas, ça ne compile pas // exemple de foobar : public void foobar(int a) throws Exception { if (a == 0) { throw new Exception("division par zéro"); } System.out.println(12 / a); } |
loguer |
error_log("ceci, celà"); # ou pour loguer dans un fichier particulier ini_set('log_errors', 1); ini_set('error_log', '/error.log'); # ou avec log4php # http://logging.apache.org/log4php/ include('log4php/Logger.php'); Logger::configure('log4php.xml'); $log = Logger::getLogger("main"); $log->info("ceci, celà"); # + fichier log4php.xml <configuration xmlns="http://logging.apache.org/log4php/"> <appender name="fichier" class="LoggerAppenderFile"> <param name="file" value="test.log" /> <layout class="LoggerLayoutPattern"> <param name="conversionPattern" value="%d{Y-m-d H:i:s.u} %-5p [%c] %F:%L - %m%n" /> </layout> </appender> <root> <level value="INFO" /> <appender_ref ref="fichier" /> </root> </configuration> |
warn("ceci, celà"); # ou avec Log4perl # sudo apt-get install liblog-log4perl-perl use Log::Log4perl; Log::Log4perl::init('log4perl.conf'); $logger = Log::Log4perl->get_logger('test'); $logger->info('ceci, celà'); # + fichier log4perl.conf : log4perl.logger.test = DEBUG, fichier log4perl.appender.fichier = Log::Log4perl::Appender::File log4perl.appender.fichier.filename = test.log log4perl.appender.fichier.layout = PatternLayout log4perl.appender.fichier.layout.ConversionPattern = %d %-5p %c [%t] %F:%L - %m%n |
import logging log = logging.getLogger('test') h = logging.FileHandler('test.log') f = logging.Formatter('%(asctime)s %(levelname)s %(name)s [%(module)s] %(filename)s:%(lineno)d %(message)s') h.setFormatter(f) log.addHandler(h) log.setLevel(logging.DEBUG) log.info('ceci, celà') |
// avec Log4j http://logging.apache.org/log4j/ PropertyConfigurator.configure("log4j.conf"); Logger log = Logger.getLogger("test"); log.info("ceci, celà"); // + fichier log4j.conf : log4j.rootLogger=debug, fichier log4j.appender.fichier=org.apache.log4j.FileAppender log4j.appender.fichier.File=test.log log4j.appender.fichier.layout=org.apache.log4j.PatternLayout log4j.appender.fichier.layout.ConversionPattern=%d %-5p %c [%t] %F:%L - %m%n |
|
particularité PHP | # afficher les erreurs d'un script # directement dans le navigateur # (en environnement de développement) ini_set('display_errors', 'on'); # ou ini_set('display_errors', 1); # ou modifier la valeur dans php.ini |
||||
manipulation de XML avec le DOM |
$doc = new DOMDocument(); $doc->load('fichier.xhtml'); foreach ($doc->getElementsByTagName("a") as $e) { echo $e->textContent."\n"; // voir aussi $e->nodeValue foreach ($e->attributes as $a) { echo $a->name." = ".$a->value."\n"; } if ($e->hasAttribute('onclick')) { echo "avant ".$e->C14N()."\n"; $e->removeAttribute('onclick'); echo "apres ".$e->C14N()."\n"; } } echo $doc->saveXML(); |
use XML::LibXML; $parser = XML::LibXML->new(); $doc = $parser ->parse_file('fichier.xhtml') ->getDocumentElement; foreach $e ($doc->getElementsByTagName("a")) { print $e->textContent."\n"; # voir aussi $e->string_value # et $e->to_literal foreach $a ($e->attributes) { print $a->name." = ".$a->value."\n"; } if ($e->hasAttribute('onclick')) { print $e->toStringC14N()."\n"; $e->removeAttribute('onclick'); print $e->toStringC14N()."\n"; } } print $doc->toString(); |
import xml.dom.minidom doc = xml.dom.minidom.parse('fichier.xhtml') for e in doc.getElementsByTagName('a'): print e.firstChild.nodeValue for k in e.attributes.keys(): print k, '=', e.attributes[k].nodeValue if e.hasAttribute('onclick'): print e.toxml() e.removeAttribute('onclick') print e.toxml() print doc.toxml() |
// à mettre à jour DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance(); DocumentBuilder b = bf.newDocumentBuilder(); Document doc = b.parse(new File("fichier.xhtml")); NodeList nl = doc.getElementsByTagName("a"); for (int i=0; i < nl.getLength(); i++) { Element elt = (Element) nl.item(i); if (elt.hasAttribute("style")) { elt.removeAttribute("style"); } } // non : System.out.println(doc.toString()); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); StringWriter sw = new StringWriter(); t.transform(new DOMSource(doc), new StreamResult(sw)); System.out.println(sw.toString()); |
|
avec XPath |
$doc = new DOMDocument(); $doc->load('fichier.xhtml'); $xp = new DOMXPath($doc); $xp->registerNamespace('x', 'http://www.w3.org/1999/xhtml'); echo $xp->query('//x:title')->item(0)->nodeValue; foreach ($xp->query('//x:td[@style]') as $e) { echo $e->nodeName." ".$e->nodeValue."\n"; } |
use XML::LibXML; $parser = XML::LibXML->new(); $doc = $parser ->parse_file('fichier.xhtml') ->getDocumentElement; $xp = XML::LibXML::XPathContext->new($doc); $xp->registerNs('x' => 'http://www.w3.org/1999/xhtml'); print $xp->findnodes('//x:title')->[0]->textContent; foreach ($xp->findnodes('//x:td[@style]')) { print $_->nodeName." ".$_->to_literal."\n"; } |
# pas avec minidom ! from lxml import etree doc = etree.parse('fichier.xhtml') ns = {'x': 'http://www.w3.org/1999/xhtml'} print doc.xpath('//x:title', namespaces=ns)[0].text for e in doc.xpath('//x:td[@style]', namespaces=ns): print e.tag, e.text # ou e.tag.split('}')[1], e.text |
||
autres versions |
$xml = simplexml_load_file('fichier.xhtml'); foreach ($xml->body->table->tbody->tr as $tr) { echo "1ere cellule : ".$tr->td[0]."\n"; foreach ($tr->children() as $e) { foreach ($e->attributes() as $a => $b) { echo "$a => $b\n"; } if (isset($e['style'])) { echo $e->getName()." ".$e['style']."\n"; unset($e['style']); } } } echo $xml->asXML(); |
use XML::Simple; # pas si simple... use Data::Dumper; $xml = XMLin('fichier.xhtml'); foreach $tr (@{$xml->{body}->{table}->{tbody}->{tr}}) { print "1ère cellule ". Dumper($tr->{td}->[0])."\n"; } |
|||
interfaces DOM et SimpleXML sur le même XML |
$xml = simplexml_load_file('fichier.xhtml'); echo $xml->head->title; // affiche le titre $doc = dom_import_simplexml($xml)->ownerDocument; $doc->getElementsByTagName('title')->item(0) ->nodeValue = 'foo'; echo $xml->head->title; // affiche foo |
||||
idem en mode "stream" (gros fichier) |
use XML::Twig; $twig = XML::Twig->new( Twig_handlers => {'a' => \&handle_a}, pretty_print => 'indented'); $twig->parsefile('fichier.xhtml'); sub handle_a { ($twig, $a) = @_; $a->del_att('style'); $twig->flush; } |
||||
manipulation XSLT |
$xml = new DOMDocument; $xml->load('donnees.xml'); $xslt = new DOMDocument; $xslt->load('transfo.xsl'); $proc = new XSLTProcessor; $proc->importStyleSheet($xslt); echo $proc->transformToXML($xml); |
use XML::LibXSLT; use XML::LibXML; $xslt = XML::LibXSLT->new(); $xml = XML::LibXML->load_xml(location => 'fichier.xml'); $xsl = XML::LibXML->load_xml(location => 'fichier.xsl'); $stylesheet = $xslt->parse_stylesheet($xsl); $transform = $stylesheet->transform($xml); print $stylesheet->output_as_bytes($transform); |
from lxml import etree doc = etree.parse('donnees.xml') xslt = etree.parse('transfo.xsl') transform = etree.XSLT(xslt) print transform(doc) |
TODO |
|
manipulation de YAML |
$a = yaml_emit(array( "nom" => "Renault", "prénom" => "Hervé", "langages" => array( "PHP", "Perl", "Python", "Java" ))); $b = yaml_parse($a); print_r($b); print $b["nom"]; |
TODO |
import yaml a = yaml.load(''' nom: Renault prénom: Hervé langages: - PHP - Perl - Python - Java ''') print a print a['nom'] |
TODO |
|
manipulation de JSON |
$a = json_encode(array( "nom" => "Renault", "prénom" => "Hervé", "langages" => array( "PHP", "Perl", "Python", "JavaScript" ))); $b = (array) json_decode($a); print_r($b); print $b["nom"]; |
use JSON; use Data::Dumper; $a = encode_json { # hashref "nom" => "Renault", "prénom" => "Hervé", "langages" => ["PHP", "Perl", "Python", "JavaScript"]}; $b= decode_json $a; print Dumper(%$b); print $b->{"nom"}; |
import json a = json.dumps({ 'nom':'Renault', 'prénom':'Hervé', 'langages': ['PHP','Perl','Python','JavaScript']}) b = json.loads(a) print b print b['nom'] |
TODO |
|
manipulation de fichier |
$f = fopen('fichier.html', 'w'); fwrite($f, $html); fclose($f); // raccourci : file_put_contents('fichier.html', $html); // plus moderne : try { $f = new \SplFileObject('fichier.html', 'w'); $f->fwrite($f, $html); unset($f); } catch (\Exception $e) { echo $e->getMessage(); } |
open($f, '> fichier.html'); print $f $html; close($f); # ou : open($f, '>', 'fichier.html'); print $f $html; close($f); |
f = open('fichier.html', 'w') f.write(html) f.close() |
FileWriter f = new FileWriter(new File("fichier.html")); f.write(html); f.close(); // avec un buffer : BufferedWriter f = new BufferedWriter(new FileWriter(new File("fichier.html"))); f.write(html); f.close(); |
|
en ajout (append) |
$f = fopen('fichier.html', 'a'); | open($f, '>>', 'fichier.html'); | f = open('fichier.html', 'a') | FileWriter f = new FileWriter("fichier.html", true); // pas besoin de new File(...) en fait |
|
fichier temporaire |
tempnam('/chemin', 'préfixe'); // renvoie le nom du fichier créé |
use File::Temp qw/ tempfile tempdir /; ($fh, $filename) = tempfile(); |
TODO |
TODO |
|
lire tout le contenu d'un fichier dans une variable |
$txt = file_get_contents("fichier.txt"); | undef $/; open($f, 'fichier.txt'); $txt = <$f>; print $txt; # ou chomp(@txt = <$f>); |
f = open('fichier.txt', 'r') txt = f.read() |
||
renommer un fichier |
rename('fichier.html', 'fichier.txt'); | rename 'fichier.html', 'fichier.txt'; # ou : use File::Copy; move('fichier.html', 'fichier.txt'); |
os.rename('fichier.html','fichier.txt') |
File a = new File("fichier.html"); a.renameTo(new File("fichier.txt")); |
|
$a = 'fichier.txt'; if (file_exists($a)) { unlink($a); } |
$a = 'fichier.txt'; if ( -e $a ) { unlink $a; } |
a = 'fichier.txt' if os.path.exists(a): os.remove(a) |
a = new File("fichier.txt"); if (a.exists()) { a.delete(); } |
||
$f = fopen($a, 'r') or die("impossible de lire le fichier
'$a'\n"); # et le motif de l'erreur est dans /var/log/... ou sur stderr |
open($f, '<', $a) or die "impossible de lire le fichier '$a' :
$!\n"; # ou use autodie; open($f, '<', $a); |
try: f = open(a, 'r') except IOError as (n, s): print "impossible de lire le fichier", a, ":", s sys.exit(1) |
try { BufferedReader f = new BufferedReader(new FileReader(a)); } catch (IOException e) { System.out.println("impossible de lire le fichier " + a + " : " + e.getMessage()); System.exit(1); } |
||
lire le contenu d'un fichier ligne par ligne |
$f = fopen($a, 'r'); while (($line = fgets($f)) != null) { echo "j'ai lu $line"; } fclose($f); |
open($f, "< $a"); while (<$f>) { print "j'ai lu $_"; } |
f = open(a, 'r') for line in f.readlines(): print "j'ai lu", line, f.close() |
String line; BufferedReader f = new BufferedReader(new FileReader(new File(a))); while ((line = f.readLine()) != null) { System.out.println("j'ai lu " + line); } |
|
fichier gzipé | $f = gzopen("fichier.gz", "r"); while (($line = fgets($f)) != null) { echo "j'ai lu $line"; } gzclose($f); |
import gzip f = gzip.open("fichier.gz", "rb") for line in f.readlines(): print "j'ai lu", line, f.close() |
|||
$a = stat("fichier.txt"); echo "Fichier modifié le : ". date("r", $a["mtime"]); // ou filemtime() dans ce cas |
use File::stat; $a = stat("fichier.txt"); print "Fichier modifié le : ". scalar(localtime $a->mtime); |
import os, time print "Fichier modidifé le : %s" % time.ctime(os.stat('fichier.txt')[8]) # ou import os.path, time print "Fichier modifié le : %s" % time.ctime(os.path.getmtime('fichier.txt')) |
TODO |
||
chmod("fichier.txt", 0755); // renvoie un booléen |
chmod 0755, "fichier.txt"; # renvoie le nombre de fichiers changés |
os.chmod("fichier.html", 0600) |
TODO |
||
lecture de répertoire |
foreach (scandir('repertoire') as $a) { if (! in_array($a, array('.','..'))) { echo "$a\n"; } } // avant PHP 5 : if ($dh = opendir('repertoire')) { while (($a = readdir($dh)) !== false) { if (! in_array($a, array('.','..'))) { echo "$a\n"; } } } |
if (opendir($dh, 'repertoire')) { while (readdir $dh) { print "$_\n" unless /^\.{1,2}$/; } } |
import os for nom in os.listdir('repertoire'): print nom |
String[] d = new File("repertoire").list(); if ( d != null) { for (String a : d) { System.out.println(a); } } |
|
restreindre à certains fichiers |
foreach (glob("*.txt") as $a) { echo "$a\n"; } |
foreach $a (glob "*.txt") { print "$a\n"; } |
import glob for a in glob.glob("*.txt"): print a |
// utiliser PathMatcher
|
|
echo basename('/foo/bar/fichier.txt'); | use File::Basename; print basename('/foo/bar/fichier.txt'); |
import os.path print os.path.basename('/foo/bar/fichier.txt') |
TODO | ||
1er paramètre d'éxecution en ligne de commande | echo $_SERVER["argv"][1]; // ou echo $argv[1]; |
print $ARGV[0]; | import sys print sys.argv[1] |
public static void main(String[] argv) { System.out.println(argv[0]); } |
|
nombre de paramètres | echo $argc; | print scalar(@ARGV); | print len(sys.argv) - 1 | System.out.println(argv.size()); | |
environnement système |
echo getenv("TERM"); |
print $ENV{"TERM"} |
import os print os.environ["TERM"] |
̶ |
System.out.println(System.getenv().get("SHELL")); |
variables pour http://... /test?foo= bar%20baz |
echo $_GET["foo"]; // bar baz echo $_POST["foo"]; echo $_REQUEST["foo"]; echo $_COOKIE["foo"]; echo $_SERVER['QUERY_STRING']; // foo=bar%20baz echo $_SERVER['REQUEST_URI']; // /test echo $_SERVER["HTTP_REFERER"]; // etc... |
use CGI; $query = CGI->new; print $query->param("foo"); print $query->cookie("foo"); print $query->query_string(); print $query->url(-relative => 1); print $query->referer(); |
import cgi form = cgi.FieldStorage() print form['foo'] |
- (utiliser un plugin jQuery) - - alert(document.cookie); // tous les cookies alert(document.location.search); // ?foo=bar%20baz alert(document.URL); // http...baz alert(document.referrer); // etc... |
|
"foo bar" |
echo urldecode("foo%20bar"); |
use URI::Escape; print uri_unescape("foo%20bar"); |
import urllib2 print urllib2.unquote('foo%20bar') |
decodeURIComponent("foo%20bar"); |
|
opérateur ternaire |
echo ($a == "A" ? "oui" : "non"); |
print ($a eq "A" ? "oui" : "non"); |
print "oui" if a == "A" else "non" |
alert(a == "A" ? "oui" : "non"); // mais attention, priorité de + alert("donc " + (a == "A" ? "oui" : "non")); |
System.out.println("A".equals(a) ? "oui" : "non"); |
variante : si a est non-vide, affiche-la, sinon affiche "non" | echo $a ?: "non"; |
? |
? |
? |
? |
version PHP 7 | echo $a ?? "non"; |
||||
temporisation en secondes |
sleep(3); |
sleep 3; |
time.sleep(3) | // pas exactement la même chose t = setTimeout('alert("fini !")',3000); |
|
temporisation inférieure à 1 seconde |
usleep(500000); |
select(undef, undef, undef, 0.5); |
time.sleep(0.5) |
setTimeout('alert("fini !")',500); | Thread.sleep(500); |
hachage MD5 |
echo md5("ceci est un test"); |
use Digest::MD5 qw(md5_hex); print md5_hex("ceci est un test"); |
import hashlib print hashlib.md5('ceci est un test').hexdigest() |
http://pajhome.org.uk/crypt/md5/ |
MessageDigest d = MessageDigest.getInstance("MD5"); BigInteger i = new BigInteger(d.digest("ceci est un test".getBytes("UTF-8"))); System.out.println(String.format("%032x", i)); // padding de zéros // ou avec les DigestUtils d'Apache Commons |
106 (un million) |
echo pow(10, 6); |
print 10 ** 6; |
print pow(10, 6) # ou print 10 ** 6 |
System.out.println(Math.pow(10, 6)); // 1000000.0 |
|
random (0 à 1) |
// Fonctions pas sûres pour le chiffrement : echo rand(0, 1000) / 1000; // mt_rand() est plus performante : echo mt_rand(0, 1000) / 1000; // Fonction sûre pour le chiffrement : echo random_int(0, 1000) / 1000; // (depuis PHP 7) |
print rand(); |
import random print random.random() |
alert(Math.random()); |
System.out.println(Math.random()); |
remplir de zéros à gauche | str_pad($a, 8, "0", STR_PAD_LEFT); | TODO | TODO | TODO | TODO |
arrondir 2.5 à 3 |
echo round(2.5); |
print int(2.5 + 0.5); |
print round(2.5) |
alert(Math.round(2.5)); |
System.out.println(Math.floor(2.5 + 0.5)); |
arrondir 2.55 à 2.6 |
echo round(2.55, 1); |
printf("%.1f", ((2.55*10)+.5)/10); |
from decimal import Decimal print Decimal(str(2.55)).quantize(Decimal('0.1')) # pas round(2.55, 1) --> 2.5 |
alert(Math.floor((2.55*10)+0.5)/10); | System.out.println(Math.floor((2.55*10)+0.5)/10); |
conversion chaîne vers nombre (avec ou sans décimale) |
$a = "123.45"; echo $a + 1; echo floatval($a) + 1; // plus sûr echo intval($a) + 1; echo (int)$a + 1; // idem |
$a = "123.45"; print $a + 1; print int($a) + 1; |
a = '23.45678' print float(a) + 1 print int(float(a)) + 1 # float() sinon ValueError |
a = "23.45678"; alert(parseFloat(a) +1 ); alert(parseInt(a) +1 ); |
String a = "23.45678"; System.out.println(Float.parseFloat(a) + 1); // Non ! System.out.println(Integer.parseInt(a) + 1); |
séparateur de décimales , au lieu de . |
echo floatval(str_replace(",", ".", "123,45")) + 1; |
$_ = "123,45"; s/,/./; print $_ + 1; |
print float('123,45'.replace(',','.')) + 1 |
TODO |
TODO |
conversion héxa <-> décimal |
echo hexdec('cc'); echo intval('cc', 16); echo 0xcc; echo dechex('204'); |
print int('cc', 16) print 0xcc print hex(204) print hex(204)[2:] # pour supprimer 0x |
alert(parseInt('cc', 16)); a = 204; alert(a.toString(16)); |
||
cosinus de 60° |
echo cos(60 / 180 * pi()); echo cos(pi() / 3); |
use Math::Trig; print cos(60 / 180 * pi); print cos(pi / 3); |
import math print math.cos(math.radians(60)) print math.cos(math.pi / 3) |
System.out.println(Math.cos(Math.toRadians(60))); System.out.println(Math.cos(Math.PI / 3)); |
|
désaccentuer |
$a = "Éluard"; setlocale(LC_ALL, 'fr_FR.UTF-8'); echo iconv('UTF-8', 'ASCII//TRANSLIT', $a); |
use utf8; use Text::Unidecode; $a = "Éluard"; print unidecode($a); |
TODO |
Notes:
<table>
la colorisation des lignes paires/impaires. Il est également possible de
coloriser des lignes (ou colonnes) paires/impaires dans presque tous les
navigateurs récents (y compris IE9 mais pas IE8) avec le sélecteur CSS :nth-child.
C'est ce que j'ai utilisé pour différencier les colonnes de cette table.
import
en Java pour ne pas
alourdir la présentation et parce que eclipse se charge très bien de les
ajouter (Shift-Control-O "Organize imports")