vbscript © 2005 stefano clemente i lucidi sono in parte realizzati con materiale tratto dal libro...
TRANSCRIPT
VBScriptVBScript
© 2005 Stefano Clemente
I lucidi sono in parte realizzati con materiale tratto dal libro di testo adottato tradotto in italiano:© 2002 Prentice Hall H. M. Deitel, P. J. Deitel, T. R. Nieto Internet & World Wide Web – How To Program (Second Edition)
Stefano [email protected]
26 Ottobre 2004 Stefano Clemente 2
IntroduzioneIntroduzione
• VBScript sta per Visual Basic Script• È un sottoinsieme di Microsoft Visual Basic• I browser MSIE contengono un interprete
VBScript• Le possibilità di VBScript per lo scripting lato
client sono simili a quelle di JavaScript−dal lato client l’uso permette di “migliorare” i
documenti XHTML
• VBScript è usato con i Server Web Microsoft per creare ASP−VBScript è lo standard de facto per ASP
26 Ottobre 2004 Stefano Clemente 3
OperatoriOperatori
• VBScript è case-insensitive
• È dotato di operatori−aritmetici−logici−di concatenazione−di confronto−relazionali
26 Ottobre 2004 Stefano Clemente 4
Operatori AritmeticiOperatori Aritmetici
OperazioneOperazione OperatoreOperatore EspressionEspressioneAlgebricaeAlgebrica
EspressioneEspressione
VBScriptVBScript
Addizione ++ x + y x + yx + y
Sottrazione –– z – 8 z – 8z – 8
Moltiplicazione ** yb y * by * b
Divisione (virgola mobile)
// v ÷ u v / uv / u
Divisione (intera) \\ v \ uv \ u
Esponenziazione ^̂ q p q ^ pq ^ p
Negazione -- -e -e-e
Modulo ModMod q mod r q Mod rq Mod r
26 Ottobre 2004 Stefano Clemente 5
Operatori LogiciOperatori Logici
OperazioneOperazione OperatoreOperatore EspressioneEspressioneLogicaLogica
EspressioneEspressione
VBScriptVBScript
And Logico AndAnd a ⋀ b a And ba And b
Or Logico OrOr a ⋁ b a Or ba Or b
Negazione Logica NotNot ¬ a Not aNot a
26 Ottobre 2004 Stefano Clemente 6
Operatori RelazionaliOperatori Relazionali
Operatore di Operatore di relazionerelazione
Operatore Operatore VBScriptVBScript Esempio Esempio
= == a = ba = b
≠ <><> a <> ba <> b
> >> a > ba > b
< << a < ba < b
≥ >=>= a >= ba >= b
≤ <=<= a <= ba <= b
26 Ottobre 2004 Stefano Clemente 7
Operatori di concatenazione Operatori di concatenazione stringhestringhe• Gli operatori di concatenazione di stringhe sono
− ++− &&
• Es: il risultato delle due operazioni− "Pro" + "gram""Pro" + "gram"− “Pro" & "gram"Pro" & "gram"
è sempre la stringa "Program""Program" • Gli operatori sono equivalenti se usati su stringhe,
mentre se uno dei due argomenti è, per esempio, di tipo numerico− "Stringa" + 2"Stringa" + 2
produce un errore di violazione dei tipi, perché VBScript cercherà di convertire "Stringa""Stringa" in un numero per eseguire una somma.
26 Ottobre 2004 Stefano Clemente 8
Tipi di datiTipi di dati• VBScript ha un solo tipo di dato, il variantvariant• Il variantvariant contiene gli altri tipi (stringhe, interi, numeri
in virgola mobile, …)• Il variantvariant è trattato in base all’informazione che
contiene• Le variabili variantvariant
− non possono essere parole riservate di VBScript− devono cominciare con una lettera− devono avere nomi con lunghezza massima di 255 caratteri− i nomi possono contenere lettere, cifre e underscore
• Una variabile è dichiarata nel momento in cui viene utilizzata
• Si può costringere a dichiarare una variabile prima di utilizzarla attraverso l’istruzioneOption ExplicitOption Explicit
26 Ottobre 2004 Stefano Clemente 9
Sottotipi di VariantSottotipi di VariantSottotipoSottotipo Intervallo/DescrizioneIntervallo/Descrizione
Boolean True o FalseTrue o False
Byte 0..2550..255
Currency ––922337203685477,5808..922337203685477,5807922337203685477,5808..922337203685477,5807
Date/Time 1/1/100..31/12/9999 / 0:00:00..23:59:59.1/1/100..31/12/9999 / 0:00:00..23:59:59.
Double ––1.79769313486232E308..–4.94065645841247E–324 (-)1.79769313486232E308..–4.94065645841247E–324 (-)
4.94065645841247E–324..1.79769313486232E308 (+)4.94065645841247E–324..1.79769313486232E308 (+)
Empty Non inizializzato: 0 per i tipi numerici, False per I boolean e "" per le stringhe
Integer ––32768..3276732768..32767
Long ––2147483648..21474836472147483648..2147483647
Object Qualsiasi tipo oggetto
Single ––3.402823E38..–1.401298E–45 (-)3.402823E38..–1.401298E–45 (-)
1.401298E–45..3.402823E38 (+)1.401298E–45..3.402823E38 (+)
String 0..~2000000000 caratteri
26 Ottobre 2004 Stefano Clemente 10
Strutture di controlloStrutture di controllo
JavaScriptJavaScript VBScriptVBScript
ifif If/Then/EndIfIf/Then/EndIf
if/elseif/else If/Then/Else/EndIfIf/Then/Else/EndIf
whilewhile While/Wend While/Wend o Do While/Loop Do While/Loop
forfor For/NextFor/Next
do/whiledo/while Do/Loop WhileDo/Loop While
switchswitch Select Case/End SelectSelect Case/End Select
Do Until/LoopDo Until/Loop
Do/Loop UntilDo/Loop Until
26 Ottobre 2004 Stefano Clemente 11
Strutture di controlloStrutture di controllo
•JavaScript
if ( s == t )if ( s == t )u = s + t;u = s + t;
else if ( s > t )else if ( s > t )u = r;u = r;
elseelseu = n;u = n;
• VBScript
If s = t ThenIf s = t Thenu = s + tu = s + t
ElseIf s > t ThenElseIf s > t Thenu = ru = r
ElseElseu = nu = n
End IfEnd If
26 Ottobre 2004 Stefano Clemente 12
Strutture di controlloStrutture di controllo
• JavaScript
switch ( x ) {switch ( x ) {case 1:case 1:
alert(“1”);alert(“1”); break; break;case 2:case 2:
alert(“2”); alert(“2”); break; break; default: default: alert(“?”); alert(“?”);}}
• VBScript
Select Case xSelect Case x Case 1 Case 1
Call Call MsgBox(“1”)MsgBox(“1”) Case 2 Case 2
Call Call MsgBox(“2”)MsgBox(“2”) Case Else Case Else
Call Call MsgBox(“?”)MsgBox(“?”)End SelectEnd Select
26 Ottobre 2004 Stefano Clemente 13
Strutture di controlloStrutture di controllo
• JavaScript
while ( !( x == 10) )while ( !( x == 10) ) ++x; ++x;
do {do { ++x; ++x;} while (!( x == 10 ));} while (!( x == 10 ));
• VBScript
Do Until x = 10Do Until x = 10 x = x + 1 x = x + 1LoopLoop
DoDo x = x + 1 x = x + 1Loop Until x = 10Loop Until x = 10
26 Ottobre 2004 Stefano Clemente 14
Strutture di controlloStrutture di controllo
• JavaScript
x = 8;x = 8;for ( y = 1; y < x; y++ )for ( y = 1; y < x; y++ ) x /= 2; x /= 2;
• VBScript
x = 8x = 8For y = 1 To xFor y = 1 To x x = x \ 2 x = x \ 2NextNext
‘ ‘ VBScriptVBScriptFor y = 2 To 20 Step 2For y = 2 To 20 Step 2 Call MsgBox( "y = " & y ) Call MsgBox( "y = " & y )NextNext
26 Ottobre 2004 Stefano Clemente 15
Esempio 1Esempio 1<?xml version = "1.0"?><?xml version = "1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">-transitional.dtd">
<!--Fig. 24.15: addition.html --><!--Fig. 24.15: addition.html --><!--Adding Integers --><!--Adding Integers --><html xmlns = <html xmlns = "http://www.w3.org/1999/xhtml">"http://www.w3.org/1999/xhtml">
<head><head> <title>Our first VBScript</title><title>Our first VBScript</title>
26 Ottobre 2004 Stefano Clemente 16
Esempio 1Esempio 1<script type = "text/vbscript"><script type = "text/vbscript"> <!--<!-- Option ExplicitOption Explicit Dim intTotalDim intTotal Sub cmdAdd_OnClick()Sub cmdAdd_OnClick() Dim intValueDim intValue intValue = InputBox(_intValue = InputBox(_ "Enter an integer", "Input Box", ,_"Enter an integer", "Input Box", ,_ 1000, 1000)1000, 1000) intTotal = CInt( intTotal ) + CInt( intValue )intTotal = CInt( intTotal ) + CInt( intValue ) Call MsgBox("You entered " & intValue & _Call MsgBox("You entered " & intValue & _ "; total so far is " & intTotal, , "; total so far is " & intTotal, ,
"Results")"Results") End SubEnd Sub -->--></script></script>
cmdAdd è il nome del bottone della formcmdAdd è il nome del bottone della formOnClick è l’eventoOnClick è l’evento
26 Ottobre 2004 Stefano Clemente 17
Esempio 1Esempio 1</head></head> <body><body> Click the button to add an integer to the Click the button to add an integer to the total.total.
<hr /><hr /> <form action = ""><form action = ""> <input name = "cmdAdd" type = "button" <input name = "cmdAdd" type = "button" value = "Click Here to Add to the value = "Click Here to Add to the Total" />Total" />
</form></form> </body></body></html></html>
26 Ottobre 2004 Stefano Clemente 18
Esempio 1Esempio 1
26 Ottobre 2004 Stefano Clemente 19
Esempio 2Esempio 2<?xml version = "1.0"?><?xml version = "1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><!-- Fig. 24.16: site.html --><!-- Fig. 24.16: site.html --><!-- Displaying a Web site --><!-- Displaying a Web site --><html xmlns = "http://www.w3.org/1999/xhtml"><html xmlns = "http://www.w3.org/1999/xhtml"> <head><head> <title>Select a site to browse</title><title>Select a site to browse</title> </head></head> <body><body> Select a site to browseSelect a site to browse <hr /><hr /> <form action = ""><form action = ""> <select name = "SiteSelector" size = "1"><select name = "SiteSelector" size = "1"> <option value = "http://www.deitel.com"><option value = "http://www.deitel.com"> Deitel & Associates, Inc.Deitel & Associates, Inc. </option></option> <option value = "http://www.prenhall.com"><option value = "http://www.prenhall.com"> Prentice HallPrentice Hall </option></option> <option value = "http://www.phptr.com/phptrinteractive"><option value = "http://www.phptr.com/phptrinteractive"> Prentice Hall InteractivePrentice Hall Interactive </option></option> </select></select>
26 Ottobre 2004 Stefano Clemente 20
Esempio 2Esempio 2 <!-- VBScript code --><!-- VBScript code --> <script for = "SiteSelector" event = <script for = "SiteSelector" event = "onchange" "onchange"
type = "text/vbscript">type = "text/vbscript"> <!-- <!-- Document.Location = _Document.Location = _ Document.Forms( 0 ).SiteSelector.ValueDocument.Forms( 0 ).SiteSelector.Value -->--> </script></script> </form></form> </body></body></html></html>
26 Ottobre 2004 Stefano Clemente 21
Esempio 2Esempio 2
26 Ottobre 2004 Stefano Clemente 22
Esempio 3Esempio 3<?xml version = "1.0"?><?xml version = "1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--Fig. 24.17: minimum.html --><!--Fig. 24.17: minimum.html --><!-- VBScript Procedures --><!-- VBScript Procedures -->
<html xmlns = "http://www.w3.org/1999/xhtml"><html xmlns = "http://www.w3.org/1999/xhtml"> <head><head> <title>Using VBScript Procedures</title><title>Using VBScript Procedures</title>
<script type = "text/vbscript"><script type = "text/vbscript"> <!--<!-- Option ExplicitOption Explicit
' Find the minimum value. Assume that first value is' Find the minimum value. Assume that first value is ' the smallest.' the smallest.
26 Ottobre 2004 Stefano Clemente 23
Esempio 3Esempio 3 Function Minimum( min, a, b )Function Minimum( min, a, b )
If a < min ThenIf a < min Then min = amin = a End IfEnd If
If b < min ThenIf b < min Then min = bmin = b End IfEnd If
Minimum = min ' Return valueMinimum = min ' Return value End FunctionEnd Function
Sub OddEven( n )Sub OddEven( n ) If n Mod 2 = 0 ThenIf n Mod 2 = 0 Then Call MsgBox( n & " is the smallest and is even" )Call MsgBox( n & " is the smallest and is even" ) ElseElse Call MsgBox( n & " is the smallest and is odd" )Call MsgBox( n & " is the smallest and is odd" ) End IfEnd If End SubEnd Sub
26 Ottobre 2004 Stefano Clemente 24
Esempio 3Esempio 3 Sub cmdButton_OnClick()Sub cmdButton_OnClick() Dim number1, number2, number3, smallestDim number1, number2, number3, smallest
' Convert each input to Long subtype' Convert each input to Long subtype number1 = CLng( Document.Forms( 0 ).txtBox1.Value )number1 = CLng( Document.Forms( 0 ).txtBox1.Value ) number2 = CLng( Document.Forms( 0 ).txtBox2.Value )number2 = CLng( Document.Forms( 0 ).txtBox2.Value ) number3 = CLng( Document.Forms( 0 ).txtBox3.Value )number3 = CLng( Document.Forms( 0 ).txtBox3.Value )
smallest = Minimum( number1, number2, number3 )smallest = Minimum( number1, number2, number3 ) Call OddEven( smallest )Call OddEven( smallest ) End SubEnd Sub -->--> </script></script> </head></head>
26 Ottobre 2004 Stefano Clemente 25
Esempio 3Esempio 3<body><body> <form action = ""> Enter a number<form action = ""> Enter a number <input type = "text" name = "txtBox1" size = "5" <input type = "text" name = "txtBox1" size = "5" value = "0" />value = "0" /> <p>Enter a number<p>Enter a number <input type = "text" name = "txtBox2" size = "5" <input type = "text" name = "txtBox2" size = "5" value = "0" /></p>value = "0" /></p> <p>Enter a number<p>Enter a number <input type = "text" name = "txtBox3" size = "5" <input type = "text" name = "txtBox3" size = "5" value = "0" /></p>value = "0" /></p> <p><input type = "button" name = "cmdButton" <p><input type = "button" name = "cmdButton" value = "Enter" /></p>value = "Enter" /></p>
</form></form> </body></body></html></html>
26 Ottobre 2004 Stefano Clemente 26
Esempio 3Esempio 3
26 Ottobre 2004 Stefano Clemente 27
ArrayArray• Gli array sono strutture dati con elementi dello
stesso tipo−array a dimensione fissaarray a dimensione fissa – la dimensione non
cambia durante l’esecuzione• DichiarazioneDim var_array ( <dimensione> )Dim var_array ( <dimensione> )
−array a dimensione variabile (redimmable redimmable arrayarray) – la dimensione può essere modificata durante l’esecuzione
• DichiarazioneDim var_array ( )Dim var_array ( )
• È possibile definire array multi-dimensionali semplicemente specificando più indici separati da virgole−Es. Dim var_array ( dimensione1, … , dimensionen )Dim var_array ( dimensione1, … , dimensionen )
26 Ottobre 2004 Stefano Clemente 28
ArrayArray• Il ridimensionamento dell’array di dimensione
variabile può essere eseguito attraverso l’istruzione ReDimReDim e può comportare− la riduzione della dimensione
• specificando una dimensione minore dell’attuale− l’ampliamento della dimensione
• specificando una dimensione maggiore dell’attuale
• Es.ReDim var_array( <nuova_dimensione> )ReDim var_array( <nuova_dimensione> )
• Il comando ReDimReDim è distruttivo e quando viene eseguito l’array perde gli elementi che contiene− i valori contenuti nell’array possono essere conservati
specificando l’opzione PreservePreserve• es: ReDim Preserve var_array ( <nuova_dimensione> )ReDim Preserve var_array ( <nuova_dimensione> )
26 Ottobre 2004 Stefano Clemente 29
ArrayArray• L’opzione PreservePreserve comporta, nel caso di riduzione della
dimensione dell’array, la perdita dei dati eccedenti la nuova dimensione e la conservazione degli altri
• Per accedere agli elementi di un array si usa la sintassivar_array( indice )var_array( indice )e il primo elemento ha indice 00 mentre l’ultimo ha indice uguale alla dimensione specificata nel comando (Re)Dim(Re)Dim
• Esistono due funzioni− LBoundLBound – restituisce il più piccolo indice dell’array (sempre 0)(sempre 0)
es: LBound ( var_array ) LBound ( var_array ) per array mono-dimensionaliLBound (var_array, numero_dimensione) LBound (var_array, numero_dimensione) per multi-dim.
− UBoundUBound – restituisce il più grande indice dell’arrayes: UBound (var_array ) UBound (var_array ) per array mono-dimensionaliUBound (var_array, numero_dimensione) UBound (var_array, numero_dimensione) per multi-dim.
• La memoria allocata per gli array dinamici può essere rilasciataErase var_arrayErase var_array− in questo caso l’array dovrà essere ridimensionato prima di essere
usato nuovamente
26 Ottobre 2004 Stefano Clemente 30
Esempio 4Esempio 4<?xml version = "1.0"?><?xml version = "1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--Fig. 24.18: arrays.html --><!--Fig. 24.18: arrays.html --><!--VBScript Arrays --><!--VBScript Arrays -->
<html xmlns = "http://www.w3.org/1999/xhtml"><html xmlns = "http://www.w3.org/1999/xhtml"> <head><head> <title>Using VBScript Arrays</title><title>Using VBScript Arrays</title>
<script type = "text/vbscript"><script type = "text/vbscript"> <!--<!-- Option ExplicitOption Explicit
Public Sub DisplayArray( x, s )Public Sub DisplayArray( x, s ) Dim jDim j
Document.Write( s & ": " )Document.Write( s & ": " ) For j = 0 To UBound( x )For j = 0 To UBound( x ) Document.Write( x( j ) & " " )Document.Write( x( j ) & " " ) NextNext Document.Write( "<br />" )Document.Write( "<br />" ) End SubEnd Sub
26 Ottobre 2004 Stefano Clemente 31
Esempio 4Esempio 4 Dim fixedSize( 3 ), fixedArray, dynamic(), kDim fixedSize( 3 ), fixedArray, dynamic(), k
ReDim dynamic( 3 ) ' Dynamically size array ReDim dynamic( 3 ) ' Dynamically size array fixedArray = Array( "A", "B", "C" )fixedArray = Array( "A", "B", "C" )
' Populate arrays with values' Populate arrays with values For k = 0 to UBound( fixedSize )For k = 0 to UBound( fixedSize ) fixedSize( k ) = 50 - kfixedSize( k ) = 50 - k dynamic( k ) = Chr( 75 + k ) dynamic( k ) = Chr( 75 + k ) NextNext ' Display contents of arrays' Display contents of arrays Call DisplayArray( fixedSize, "fixedSize" )Call DisplayArray( fixedSize, "fixedSize" ) Call DisplayArray( fixedArray, "fixedArray" )Call DisplayArray( fixedArray, "fixedArray" ) Call DisplayArray( dynamic, "dynamic" )Call DisplayArray( dynamic, "dynamic" )
' Resize dynamic, preserve current values' Resize dynamic, preserve current values ReDim Preserve dynamic( 5 )ReDim Preserve dynamic( 5 ) dynamic( 4 ) = 3.343dynamic( 4 ) = 3.343 dynamic( 5 ) = 77.37443dynamic( 5 ) = 77.37443
Call DisplayArray( dynamic, "dynamic after ReDim Preserve" )Call DisplayArray( dynamic, "dynamic after ReDim Preserve" ) --> --> </script></script> </head><body></body></head><body></body></html></html>
26 Ottobre 2004 Stefano Clemente 32
Esempio 4Esempio 4
26 Ottobre 2004 Stefano Clemente 33
Manipolazione di stringheManipolazione di stringhe• Una delle caratteristiche più potenti di
VBScript è la manipolazione di stringhe• Le stringhe sono case-sensitiveLe stringhe sono case-sensitive• I caratteri di una stringa sono numerabili per
mezzo di indici−Il primo carattere ha indice 1
• VBScript dispone di diverse funzioni per la manipolazione di stringhe
• La maggior parte di queste funzioni non modificano la stringa, ma restituiscono come risultato una stringa corrispondente alla stringa modificata
26 Ottobre 2004 Stefano Clemente 34
Funzioni per la manipolazione di Funzioni per la manipolazione di stringhestringheFunzioneFunzione DescrizioneDescrizione
AscAsc Restituisce il codice ASCII di un carattere. Es. Asc("x") = 120.
ChrChr Restituisce il carattere relativo a un codice ASCII. Es. Chr(120) = “x” L’argomento deve essere un intero compreso tra 0 e 255, altrimenti viene restituito un errore.
InStrInStr Verifica se una stringa (primo argomento) contiene una sottostringa (secondo argomento). La ricerca è fatta da sinistra verso destra. In caso di successo restituisce l’indice del primo carattere della stringa corrispondente al primo della sottostringa, altrimenti restituisce 0. Es. Instr("sparrow","arrow") = 3, Instr("japan","wax") = 0.
LenLen Restituisce il numero di caratteri della stringa. Len("hello") = 5.
LCaseLCase Restituisce la stringa passata come argomento, ma con soli caratteri minuscoli. Es. LCase("HELLO@97[") = “hello@97[”
UCaseUCase Restituisce la stringa passata come argomento, ma con soli caratteri maiuscoli. Es. UCase("hello@97[") returns “HELLO@97[”
LeftLeft Restituisce i primi n (secondo argomento) caratteri più a sinistra di una stringa (primo argomento). Es. Left("Web",2) = “We”
26 Ottobre 2004 Stefano Clemente 35
Funzioni per la manipolazione di Funzioni per la manipolazione di stringhestringheFunzioneFunzione DescrizioneDescrizione
MidMid Restituisce gli n (terzo argomento) caratteri di una stringa (primo argomento) a partire dalla posizione m (secondo argomento). Es.Mid("abcd",2,3)= “bcd”
RightRight Restituisce i primi n (secondo argomento) caratteri più a destra di una stringa (primo argomento). Es. Right("Web",2) returns “eb”
SpaceSpace Restituisce una stringa di n (argomento) spazi. Es. Space(4)restituisce una stringa di 4 spazi
StrCompStrComp Verifica l’uguaglianza di due stringhe e restituisce 1 se la prima stringa è maggiore della seconda, -1 se la prima stringa è minore della seconda, 0 se le stringhe sono equivalenti. Il confronto di default è binario (=, case-sensitive). Passando come terzo argomento vbTextCompare è possibile eseguire un confronto case-insensitive . Es. StrComp("bcd", "BCD") = 1, StrComp("BCD", "bcd")= -1, StrComp("bcd", "bcd") = 0, StrComp("bcd", "BCD", vbTextCompare)= 0
StringString Restituisce una stringa in cui un carattere (primo argomento) è ripetuto n volte (secondo argomento). Es. String(4,"u")= “uuuu”
TrimTrim Restituisce una stringa senza spazi all’inizio e alla fine. Es. Trim(" hi ")= “hi”
LTrimLTrim Restituisce una stringa senza spazi all’inizio. Es. LTrim(" yes")= “yes”
26 Ottobre 2004 Stefano Clemente 36
Funzioni per la manipolazione di Funzioni per la manipolazione di stringhestringhe
FunzionFunzionee
DescrizioneDescrizione
RTrimRTrim Restituisce una stringa senza spazi alla fine. Es. RTrim("no ") = “no”
FilterFilter Restituisce un array di stringhe contenente il risultato dell’operazione di filtraggio Es. Filter(Array("A","S","D","F","G","D"),"D") restituisce un array di due elementi contenente "D" e "D", mentre Filter(Array("A","S","D","F","G","D"),"D",False) restituisce un array contenente "A" , "S", "F" e "G"
JoinJoin Restituisce una stringa contenente la concatenazione di elementi Array separati da un delimitatore, eventualmente passato come secondo argomento opzionale (default = spazio). Es Join(Array("one","two","three")) = “one two three.” , Join(Array("one","two","three"),"$^") = “one$^two$^three”
ReplaceReplace Restituisce una stringa. Richiede tre argomenti, la stringa nella quale si vogliono sostituire dei caratteri, la sottostringa da cercare e la sottostringa con la quale si vuole sostituire (è case-sensitive). Es. Replace("It's Sunday and the sun is out","sun","moon") = “It's Sunday and the moon is out”
26 Ottobre 2004 Stefano Clemente 37
Funzioni per la manipolazione di Funzioni per la manipolazione di stringhestringhe
FunzioneFunzione DescrizioneDescrizione
SplitSplit Restituisce un array di sottostringhe della stringa passata come argomento. La stringa viene divisa considerando per default lo spazio come separatore, un carattere separatore diverso può essere passato come secondo argomento (opzionale). Es. Split("I met a traveller") restituisce "I", "met", "a" e "traveller" Split("red,white,and blue", ",") restituisce "red", "white" e "and blue"
StrReverseStrReverse Restituisce una stringa (argomento) in ordine inverso. Es. StrReverse("deer") = “reed”
InStrRevInStrRev Verifica se una stringa (primo argomento) contiene una sottostringa (secondo argomento). La ricerca è fatta da destra verso sinistra. In caso di successo restituisce l’indice del primo carattere della stringa corrispondente al primo della sottostringa, altrimenti restituisce 0. es.InstrRev("sparrow","arrow") = 3InstrRev("japan","wax") = 0 InstrRev("to be or not to be","to be") = 14
26 Ottobre 2004 Stefano Clemente 38
Esempio 5Esempio 5<?xml version = "1.0"?><?xml version = "1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">transitional.dtd">
<!--Fig. 24.20: piglatin.html --><!--Fig. 24.20: piglatin.html --><!-- VBscript String Functions --><!-- VBscript String Functions -->
<html xmlns = "http://www.w3.org/1999/xhtml"><html xmlns = "http://www.w3.org/1999/xhtml"> <head><head> <title>Using VBScript String Functions</title><title>Using VBScript String Functions</title>
<script type = "text/vbscript"><script type = "text/vbscript"> <!--<!-- Option ExplicitOption Explicit
26 Ottobre 2004 Stefano Clemente 39
Esempio 5Esempio 5 Public Function TranslateToPigLatin( englishPhrase ) Public Function TranslateToPigLatin( englishPhrase )
Dim words ' Stores each individual wordDim words ' Stores each individual word Dim k, suffixDim k, suffix
' Get each word and store in words the' Get each word and store in words the ' default delimiter for Split is a space' default delimiter for Split is a space words = Split( englishPhrase )words = Split( englishPhrase ) For k = 0 to UBound( words )For k = 0 to UBound( words ) ' Check if first letter is a vowel' Check if first letter is a vowel If InStr( 1, "aeiou", _If InStr( 1, "aeiou", _ LCase( Left( words( k ), 1 ) ) ) ThenLCase( Left( words( k ), 1 ) ) ) Then suffix = "y"suffix = "y" ElseElse suffix = "ay"suffix = "ay" End IfEnd If
26 Ottobre 2004 Stefano Clemente 40
Esempio 5Esempio 5 ' Convert the word to pig Latin' Convert the word to pig Latin words( k ) = Right( words( k ), _words( k ) = Right( words( k ), _ Len( words( k ) ) - 1 ) & _Len( words( k ) ) - 1 ) & _ Left( words( k ), 1 ) & suffix Left( words( k ), 1 ) & suffix NextNext ' Return translated phrase, each word ' Return translated phrase, each word ' is separated by spaces' is separated by spaces TranslateToPigLatin = Join( words )TranslateToPigLatin = Join( words ) End FunctionEnd Function
Sub cmdButton_OnClick()Sub cmdButton_OnClick() Dim phraseDim phrase
phrase = Document.Forms( 0 ).txtInput.Valuephrase = Document.Forms( 0 ).txtInput.Value Document.forms( 0 ).txtPigLatin.Value = _ Document.forms( 0 ).txtPigLatin.Value = _
TranslateToPigLatin( phrase )TranslateToPigLatin( phrase ) End SubEnd Sub -->--> </script></script> </head></head>
26 Ottobre 2004 Stefano Clemente 41
Esempio 5Esempio 5<body><body> <form action = ""> Enter a sentence<form action = ""> Enter a sentence <input type = "text" name = "txtInput" <input type = "text" name = "txtInput" size = "50" />size = "50" />
<p>Pig Latin<p>Pig Latin <input type = "text" name = <input type = "text" name = "txtPigLatin" size = "70" />"txtPigLatin" size = "70" />
</p><p></p><p> <input type = "button" name = <input type = "button" name = "cmdButton" "cmdButton"
value = "Translate" /></p>value = "Translate" /></p> </form></form> </body></body></html></html>
26 Ottobre 2004 Stefano Clemente 42
Esempio 5Esempio 5
26 Ottobre 2004 Stefano Clemente 43
Classi e OggettiClassi e Oggetti
• In VBScript l’unità della programmazione OO è la classe (ClassClass) dalla quale gli oggetti sono creati (istanziati)
• I metodi sono procedure VBScript incapsulate all’interno delle classi insieme ai dati che esse elaborano
• Le classi sono un modo attraverso il quale gli utenti possono creare nuovi tipi di dati, definendo−i dati (le variabili)−le operazioni permesse sui dati (i metodi)
26 Ottobre 2004 Stefano Clemente 44
Classi e OggettiClassi e Oggetti• Le classi nascondono la loro implementazione
all’utente (information hidinginformation hiding)− l’utente può anche conoscere alcuni dettagli implementativi
della classe, ma l’unico modo per interagire con essa è attraverso i metodi che la classe mette a disposizione
• Class dispone di − dati privati (PrivatePrivate) – dati modificabili solo dalla classe− metodi richiamabili dall’utente (PublicPublic) – permettono
all’utente di modificare/visualizzare i dati PrivatePrivate• Property LetProperty Let – modifica dati che non sono sottotipi dell’oggetto
(interi, stringhe, ecc.)• Property SetProperty Set – modifica dati che sono sottotipi dell’oggetto• Property GetProperty Get – restituisce il valore dei dati
26 Ottobre 2004 Stefano Clemente 45
Esempio 6Esempio 6<?xml version = "1.0"?><?xml version = "1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">transitional.dtd">
<!--Fig. 24.24: classes.html --><!--Fig. 24.24: classes.html --><!-- VBScript Class --><!-- VBScript Class -->
<html xmlns = "http://www.w3.org/1999/xhtml"><html xmlns = "http://www.w3.org/1999/xhtml"> <head><head> <title>Using a VBScript Class</title><title>Using a VBScript Class</title>
<script type = "text/vbscript"><script type = "text/vbscript"><!--<!--
Option ExplicitOption Explicit
26 Ottobre 2004 Stefano Clemente 46
Esempio 6Esempio 6 Class PersonClass Person Private name, yearsOld, ssnPrivate name, yearsOld, ssn Public Property Let FirstName( fn )Public Property Let FirstName( fn ) name = fnname = fn End PropertyEnd Property
Public Property Get FirstName()Public Property Get FirstName() FirstName = nameFirstName = name End Property End Property
Public Property Let Age( a )Public Property Let Age( a ) yearsOld = ayearsOld = a End PropertyEnd Property
Public Property Get Age()Public Property Get Age() Age = yearsOldAge = yearsOld End PropertyEnd Property
26 Ottobre 2004 Stefano Clemente 47
Esempio 6Esempio 6 Public Property Let SocialSecurityNumber( n )Public Property Let SocialSecurityNumber( n ) If Validate( n ) ThenIf Validate( n ) Then ssn = nssn = n ElseElse ssn = "000-00-0000"ssn = "000-00-0000" Call MsgBox( "Invalid Social Security Call MsgBox( "Invalid Social Security Format" )Format" )
End If End If End PropertyEnd Property
Public Property Get SocialSecurityNumber()Public Property Get SocialSecurityNumber() SocialSecurityNumber = ssnSocialSecurityNumber = ssn End PropertyEnd Property
26 Ottobre 2004 Stefano Clemente 48
Esempio 6Esempio 6 Private Function Validate( expression )Private Function Validate( expression ) Dim regularExpressionDim regularExpression Set regularExpression = New RegExpSet regularExpression = New RegExp
regularExpression.Pattern = "^\d{3}-\d{2}-\d{4}$"regularExpression.Pattern = "^\d{3}-\d{2}-\d{4}$"
If regularExpression.Test( expression ) ThenIf regularExpression.Test( expression ) Then Validate = TrueValidate = True ElseElse Validate = FalseValidate = False End IfEnd If
End FunctionEnd Function
Public Function ToString()Public Function ToString() ToString = name & Space( 3 ) & age & Space( 3 ) & ssnToString = name & Space( 3 ) & age & Space( 3 ) & ssn End FunctionEnd Function
End Class ' PersonEnd Class ' Person
26 Ottobre 2004 Stefano Clemente 49
Esempio 6Esempio 6 Sub cmdButton_OnClick()Sub cmdButton_OnClick() Dim p ' Declare object referenceDim p ' Declare object reference Set p = New Person ' Instantiate Person objectSet p = New Person ' Instantiate Person object
With pWith p .FirstName = Document.Forms(0).txtBox1.Value.FirstName = Document.Forms(0).txtBox1.Value .Age = CInt( Document.Forms(0).txtBox2.Value ).Age = CInt( Document.Forms(0).txtBox2.Value ) .SocialSecurityNumber =_ .SocialSecurityNumber =_ Document.Forms(0).txtBox3.ValueDocument.Forms(0).txtBox3.Value Call MsgBox( .ToString() ) Call MsgBox( .ToString() ) End With End With
End SubEnd Sub -->--> </script></script> </head></head>
26 Ottobre 2004 Stefano Clemente 50
Esempio 6Esempio 6<body><body> <form action = "">Enter first name<form action = "">Enter first name <input type = "text" name = "txtBox1" size = <input type = "text" name = "txtBox1" size =
"10" /> "10" /> <p>Enter age<p>Enter age <input type = "text" name = "txtBox2" size = "5" <input type = "text" name = "txtBox2" size = "5"
/></p>/></p> <p>Enter social security number<p>Enter social security number <input type = "text" name = "txtBox3" size = <input type = "text" name = "txtBox3" size =
"10" /> "10" /> </p><p></p><p> <input type = "button" name = "cmdButton" <input type = "button" name = "cmdButton" value = "Enter" /></p>value = "Enter" /></p> </form></form> </body></body></html></html>
26 Ottobre 2004 Stefano Clemente 51
Esempio 6Esempio 6
26 Ottobre 2004 Stefano Clemente 52
Esempio 6Esempio 6