Total Pageviews

Friday 27 January 2012

RK QTP Classes2


VBSCRIPT LANGUAGE OVERVIEW:


Vbscript data types:
What Are VBScript Data Types?
VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it's used. Because Variant is the only data type in VBScript, it's also the data type returned by all functions in VBScript.
At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when you use it in a numeric context and as a string when you use it in a string context. That is, if you're working with data that looks like numbers, VBScript assumes that it is numbers and does the thing that is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. Of course, you can always make numbers behave as strings by enclosing them in quotation marks (" ").
Variant Subtypes
Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information. For example, you can have numeric information that represents a date or a time. When used with other date or time data, the result is always expressed as a date or a time. Of course, you can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. These different categories of information that can be contained in a Variant are called subtypes. Most of the time, you can just put the kind of data you want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains.
The following table shows the subtypes of data that a Variant can contain.
Subtype
Description
Empty
Variant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.
Null
Variant intentionally contains no valid data.
Boolean
Contains either True or False.
Byte
Contains integer in the range 0 to 255.
Integer
Contains integer in the range -32,768 to 32,767.
Currency
-922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long
Contains integer in the range -2,147,483,648 to 2,147,483,647.
Single
Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double
Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Date (Time)
Contains a number that represents a date between January 1, 100 to December 31, 9999.
String
Contains a variable-length string that can be up to approximately 2 billion characters in length.
Object
Contains an object.
Error
Contains an error number.
You can use conversion functions to convert data from one subtype to another. In addition, the VarType function returns information about how your data is stored within a Variant.
vbscript variable type:
VBScript Constants

 What Is a Constant?
A constant is a meaningful name that takes the place of a number or string and never changes. VBScript defines a number of intrinsic constants. You can get information about these intrinsic constants from the VBScript Language Reference.
Creating Constants
You create user-defined constants in VBScript using the Const statement. Using the Const statement, you can create string or numeric constants with meaningful names and assign them literal values. For example:
Const MyString = "This is my string."
Const MyAge = 49
Note that the string literal is enclosed in quotation marks (" "). Quotation marks are the most obvious way to differentiate string values from numeric values. Date literals and time literals are represented by enclosing them in number signs (#). For example:
Const CutoffDate = #6-1-97#
You may want to adopt a naming scheme to differentiate constants from variables. This will prevent you from trying to reassign constant values while your script is running. For example, you might want to use a "vb" or "con" prefix on your constant names, or you might name your constants in all capital letters. Differentiating constants from variables eliminates confusion as you develop more complex scripts.
conditional statements:

Loops

A loop is a block of code that iterates [1] a list of commands as long as the loop control condition is true.
for loops
for arg in [list]
This is the basic looping construct. It differs significantly from its C counterpart.
for arg in [list]
do 
 command(s)... 
done
During each pass through the loop, arg takes on the value of each successive variable in the list.
for arg in "$var1" "$var2" "$var3" ... "$varN"  
# In pass 1 of the loop, arg = $var1     
# In pass 2 of the loop, arg = $var2     
# In pass 3 of the loop, arg = $var3     
# ...
# In pass N of the loop, arg = $varN
 
# Arguments in [list] quoted to prevent possible word splitting.
The argument list may contain wild cards.
If do is on same line as for, there needs to be a semicolon after list.
for arg in [list] ; do 
Example 11-1. Simple for loops
#!/bin/bash
# Listing the planets.
 
for planet in Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto
do
  echo $planet  # Each planet on a separate line.
done
 
echo; echo
 
for planet in "Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto"
    # All planets on same line.
    # Entire 'list' enclosed in quotes creates a single variable.
    # Why? Whitespace incorporated into the variable.
do
  echo $planet
done
 
echo; echo "Whoops! Pluto is no longer a planet!"
 
exit 0
Each [list] element may contain multiple parameters. This is useful when processing parameters in groups. In such cases, use the set command (see Example 15-16) to force parsing of each [list] element and assignment of each component to the positional parameters.
Example 11-2. for loop with two parameters in each [list] element
#!/bin/bash
# Planets revisited.
 
# Associate the name of each planet with its distance from the sun.
 
for planet in "Mercury 36" "Venus 67" "Earth 93"  "Mars 142" "Jupiter 483"
do
  set -- $planet  #  Parses variable "planet"
                  #+ and sets positional parameters.
  #  The "--" prevents nasty surprises if $planet is null or
  #+ begins with a dash.
 
  #  May need to save original positional parameters,
  #+ since they get overwritten.
  #  One way of doing this is to use an array,
  #         original_params=("$@")
 
  echo "$1                             $2,000,000 miles from the sun"
  #-------two  tabs---concatenate zeroes onto parameter $2
done
 
# (Thanks, S.C., for additional clarification.)
 
exit 0
A variable may supply the [list] in a for loop.
Example 11-3. Fileinfo: operating on a file list contained in a variable
#!/bin/bash
# fileinfo.sh
 
FILES="/usr/sbin/accept
/usr/sbin/pwck
/usr/sbin/chroot
/usr/bin/fakefile
/sbin/badblocks
/sbin/ypbind"     # List of files you are curious about.
                  # Threw in a dummy file, /usr/bin/fakefile.
 
echo
 
for file in $FILES
do
 
  if [ ! -e "$file" ]       # Check if file exists.
  then
    echo "$file does not exist."; echo
    continue                # On to next.
   fi
 
  ls -l $file | awk '{ print $8 "         file size: " $5 }'  # Print 2 fields.
  whatis `basename $file`   # File info.
  # Note that the whatis database needs to have been set up for this to work.
  # To do this, as root run /usr/bin/makewhatis.
  echo
done  
 
exit 0
If the [list] in a for loop contains wild cards (* and ?) used in filename expansion, then globbing takes place.
Example 11-4. Operating on files with a for loop
#!/bin/bash
# list-glob.sh: Generating [list] in a for-loop, using "globbing"
 
echo
 
for file in *
#           ^  Bash performs filename expansion
#+             on expressions that globbing recognizes.
do
  ls -l "$file"  # Lists all files in $PWD (current directory).
  #  Recall that the wild card character "*" matches every filename,
  #+ however, in "globbing," it doesn't match dot-files.
 
  #  If the pattern matches no file, it is expanded to itself.
  #  To prevent this, set the nullglob option
  #+   (shopt -s nullglob).
  #  Thanks, S.C.
done
 
echo; echo
 
for file in [jx]*
do
  rm -f $file    # Removes only files beginning with "j" or "x" in $PWD.
  echo "Removed file \"$file\"".
done
 
echo
 
exit 0
Omitting the in [list] part of a for loop causes the loop to operate on $@ -- the positional parameters. A particularly clever illustration of this is Example A-15. See also Example 15-17.
Example 11-5. Missing in [list] in a for loop
#!/bin/bash
 
#  Invoke this script both with and without arguments,
#+ and see what happens.
 
for a
do
 echo -n "$a "
done
 
#  The 'in list' missing, therefore the loop operates on '$@'
#+ (command-line argument list, including whitespace).
 
echo
 
exit 0
It is possible to use command substitution to generate the [list] in a for loop. See also Example 16-54, Example 11-10 and Example 16-48.
Example 11-6. Generating the [list] in a for loop with command substitution
#!/bin/bash
#  for-loopcmd.sh: for-loop with [list]
#+ generated by command substitution.
 
NUMBERS="9 7 3 8 37.53"
 
for number in `echo $NUMBERS`  # for number in 9 7 3 8 37.53
do
  echo -n "$number "
done
 
echo 
exit 0
Here is a somewhat more complex example of using command substitution to create the [list].
Example 11-7. A grep replacement for binary files
#!/bin/bash
# bin-grep.sh: Locates matching strings in a binary file.
 
# A "grep" replacement for binary files.
# Similar effect to "grep -a"
 
E_BADARGS=65
E_NOFILE=66
 
if [ $# -ne 2 ]
then
  echo "Usage: `basename $0` search_string filename"
  exit $E_BADARGS
fi
 
if [ ! -f "$2" ]
then
  echo "File \"$2\" does not exist."
  exit $E_NOFILE
fi  
 
 
IFS=$'\012'       # Per suggestion of Anton Filippov.
                  # was:  IFS="\n"
for word in $( strings "$2" | grep "$1" )
# The "strings" command lists strings in binary files.
# Output then piped to "grep", which tests for desired string.
do
  echo $word
done
 
# As S.C. points out, lines 23 - 30 could be replaced with the simpler
#    strings "$2" | grep "$1" | tr -s "$IFS" '[\n*]'
 
 
#  Try something like  "./bin-grep.sh mem /bin/ls"
#+ to exercise this script.
 
exit 0
More of the same.
Example 11-8. Listing all users on the system
#!/bin/bash
# userlist.sh
 
PASSWORD_FILE=/etc/passwd
n=1           # User number
 
for name in $(awk 'BEGIN{FS=":"}{print $1}' < "$PASSWORD_FILE" )
# Field separator = :    ^^^^^^
# Print first field              ^^^^^^^^
# Get input from password file               ^^^^^^^^^^^^^^^^^
do
  echo "USER #$n = $name"
  let "n += 1"
done  
 
 
# USER #1 = root
# USER #2 = bin
# USER #3 = daemon
# ...
# USER #30 = bozo
 
exit $?
 
#  Discussion:
#  ----------
#  How is it that an ordinary user, or a script run by same,
#+ can read /etc/passwd? (Hint: Check the /etc/passwd file permissions.)
#  Isn't this a security hole? Why or why not?
Yet another example of the [list] resulting from command substitution.
Example 11-9. Checking all the binaries in a directory for authorship
#!/bin/bash
# findstring.sh:
# Find a particular string in the binaries in a specified directory.
 
directory=/usr/bin/
fstring="Free Software Foundation"  # See which files come from the FSF.
 
for file in $( find $directory -type f -name '*' | sort )
do
  strings -f $file | grep "$fstring" | sed -e "s%$directory%%"
  #  In the "sed" expression,
  #+ it is necessary to substitute for the normal "/" delimiter
  #+ because "/" happens to be one of the characters filtered out.
  #  Failure to do so gives an error message. (Try it.)
done  
 
exit $?
 
#  Exercise (easy):
#  ---------------
#  Convert this script to take command-line parameters
#+ for $directory and $fstring.
A final example of [list] / command substitution, but this time the "command" is a function.
generate_list ()
{
  echo "one two three"
}
 
for word in $(generate_list)  # Let "word" grab output of function.
do
  echo "$word"
done
 
# one
# two
# three
The output of a for loop may be piped to a command or commands.
Example 11-10. Listing the symbolic links in a directory
#!/bin/bash
# symlinks.sh: Lists symbolic links in a directory.
 
 
directory=${1-`pwd`}
#  Defaults to current working directory,
#+ if not otherwise specified.
#  Equivalent to code block below.
# ----------------------------------------------------------
# ARGS=1                 # Expect one command-line argument.
#
# if [ $# -ne "$ARGS" ]  # If not 1 arg...
# then
#   directory=`pwd`      # current working directory
# else
#   directory=$1
# fi
# ----------------------------------------------------------
 
echo "symbolic links in directory \"$directory\""
 
for file in "$( find $directory -type l )"   # -type l = symbolic links
do
  echo "$file"
done | sort                                  # Otherwise file list is unsorted.
#  Strictly speaking, a loop isn't really necessary here,
#+ since the output of the "find" command is expanded into a single word.
#  However, it's easy to understand and illustrative this way.
 
#  As Dominik 'Aeneas' Schnitzer points out,
#+ failing to quote  $( find $directory -type l )
#+ will choke on filenames with embedded whitespace.
#  containing whitespace. 
 
exit 0
 
 
# --------------------------------------------------------
# Jean Helou proposes the following alternative:
 
echo "symbolic links in directory \"$directory\""
# Backup of the current IFS. One can never be too cautious.
OLDIFS=$IFS
IFS=:
 
for file in $(find $directory -type l -printf "%p$IFS")
do     #                              ^^^^^^^^^^^^^^^^
       echo "$file"
       done|sort
 
# And, James "Mike" Conley suggests modifying Helou's code thusly:
 
OLDIFS=$IFS
IFS='' # Null IFS means no word breaks
for file in $( find $directory -type l )
do
  echo $file
  done | sort
 
#  This works in the "pathological" case of a directory name having
#+ an embedded colon.
#  "This also fixes the pathological case of the directory name having
#+  a colon (or space in earlier example) as well."
The stdout of a loop may be redirected to a file, as this slight modification to the previous example shows.
Example 11-11. Symbolic links in a directory, saved to a file
#!/bin/bash
# symlinks.sh: Lists symbolic links in a directory.
 
OUTFILE=symlinks.list                         # save file
 
directory=${1-`pwd`}
#  Defaults to current working directory,
#+ if not otherwise specified.
 
 
echo "symbolic links in directory \"$directory\"" > "$OUTFILE"
echo "---------------------------" >> "$OUTFILE"
 
for file in "$( find $directory -type l )"    # -type l = symbolic links
do
  echo "$file"
done | sort >> "$OUTFILE"                     # stdout of loop
#           ^^^^^^^^^^^^^                       redirected to save file.
 
exit 0
There is an alternative syntax to a for loop that will look very familiar to C programmers. This requires double parentheses.
Example 11-12. A C-style for loop
#!/bin/bash
# Multiple ways to count up to 10.
 
echo
 
# Standard syntax.
for a in 1 2 3 4 5 6 7 8 9 10
do
  echo -n "$a "
done  
 
echo; echo
 
# +==========================================+
 
# Using "seq" ...
for a in `seq 10`
do
  echo -n "$a "
done  
 
echo; echo
 
# +==========================================+
 
# Using brace expansion ...
# Bash, version 3+.
for a in {1..10}
do
  echo -n "$a "
done  
 
echo; echo
 
# +==========================================+
 
# Now, let's do the same, using C-like syntax.
 
LIMIT=10
 
for ((a=1; a <= LIMIT ; a++))  # Double parentheses, and "LIMIT" with no "$".
do
  echo -n "$a "
done                           # A construct borrowed from 'ksh93'.
 
echo; echo
 
# +=========================================================================+
 
# Let's use the C "comma operator" to increment two variables simultaneously.
 
for ((a=1, b=1; a <= LIMIT ; a++, b++))
do  # The comma chains together operations.
  echo -n "$a-$b "
done
 
echo; echo
 
exit 0
---
Now, a for loop used in a "real-life" context.
Example 11-13. Using efax in batch mode
#!/bin/bash
# Faxing (must have 'efax' package installed).
 
EXPECTED_ARGS=2
E_BADARGS=85
MODEM_PORT="/dev/ttyS2"   # May be different on your machine.
#                ^^^^^      PCMCIA modem card default port.
 
if [ $# -ne $EXPECTED_ARGS ]
# Check for proper number of command-line args.
then
   echo "Usage: `basename $0` phone# text-file"
   exit $E_BADARGS
fi
 
 
if [ ! -f "$2" ]
then
  echo "File $2 is not a text file."
  #     File is not a regular file, or does not exist.
  exit $E_BADARGS
fi
  
 
fax make $2              #  Create fax-formatted files from text files.
 
for file in $(ls $2.0*)  #  Concatenate the converted files.
                         #  Uses wild card (filename "globbing")
                                               #+ in variable list.
do
  fil="$fil $file"
done  
 
efax -d "$MODEM_PORT"  -t "T$1" $fil   # Finally, do the work.
# Trying adding  -o1  if above line fails.
 
 
#  As S.C. points out, the for-loop can be eliminated with
#     efax -d /dev/ttyS2 -o1 -t "T$1" $2.0*
#+ but it's not quite as instructive [grin].
 
exit $?   # Also, efax sends diagnostic messages to stdout.
while
This construct tests for a condition at the top of a loop, and keeps looping as long as that condition is true (returns a 0 exit status). In contrast to a for loop, a while loop finds use in situations where the number of loop repetitions is not known beforehand.
while [ condition ]
do 
 command(s)... 
done
The bracket construct in a while loop is nothing more than our old friend, the test brackets used in an if/then test. In fact, a while loop can legally use the more versatile double-brackets construct (while [[ condition ]]).
As is the case with for loops, placing the do on the same line as the condition test requires a semicolon.
while [ condition ] ; do
Note that the test brackets are not mandatory in a while loop. See, for example, the getopts construct.
Example 11-14. Simple while loop
#!/bin/bash
 
var0=0
LIMIT=10
 
while [ "$var0" -lt "$LIMIT" ]
#      ^                    ^
# Spaces, because these are "test-brackets" . . .
do
  echo -n "$var0 "        # -n suppresses newline.
  #             ^           Space, to separate printed out numbers.
 
  var0=`expr $var0 + 1`   # var0=$(($var0+1))  also works.
                          # var0=$((var0 + 1)) also works.
                          # let "var0 += 1"    also works.
done                      # Various other methods also work.
 
echo
 
exit 0
Example 11-15. Another while loop
#!/bin/bash
 
echo
                               # Equivalent to:
while [ "$var1" != "end" ]     # while test "$var1" != "end"
do
  echo "Input variable #1 (end to exit) "
  read var1                    # Not 'read $var1' (why?).
  echo "variable #1 = $var1"   # Need quotes because of "#" . . .
  # If input is 'end', echoes it here.
  # Does not test for termination condition until top of loop.
  echo
done  
 
exit 0
A while loop may have multiple conditions. Only the final condition determines when the loop terminates. This necessitates a slightly different loop syntax, however.
Example 11-16. while loop with multiple conditions
#!/bin/bash
 
var1=unset
previous=$var1
 
while echo "previous-variable = $previous"
      echo
      previous=$var1
      [ "$var1" != end ] # Keeps track of what $var1 was previously.
      # Four conditions on "while", but only last one controls loop.
      # The *last* exit status is the one that counts.
do
echo "Input variable #1 (end to exit) "
  read var1
  echo "variable #1 = $var1"
done  
 
# Try to figure out how this all works.
# It's a wee bit tricky.
 
exit 0
As with a for loop, a while loop may employ C-style syntax by using the double-parentheses construct (see also Example 8-5).
Example 11-17. C-style syntax in a while loop
#!/bin/bash
# wh-loopc.sh: Count to 10 in a "while" loop.
 
LIMIT=10                 # 10 iterations.
a=1
 
while [ "$a" -le $LIMIT ]
do
  echo -n "$a "
  let "a+=1"
done                     # No surprises, so far.
 
echo; echo
 
# +=================================================================+
 
# Now, we'll repeat with C-like syntax.
 
((a = 1))      # a=1
# Double parentheses permit space when setting a variable, as in C.
 
while (( a <= LIMIT ))   #  Double parentheses,
do                       #+ and no "$" preceding variables.
  echo -n "$a "
  ((a += 1))             # let "a+=1"
  # Yes, indeed.
  # Double parentheses permit incrementing a variable with C-like syntax.
done
 
echo
 
# C and Java programmers can feel right at home in Bash.
 
exit 0
Inside its test brackets, a while loop can call a function.
t=0
 
condition ()
{
  ((t++))
 
  if [ $t -lt 5 ]
  then
    return 0  # true
  else
    return 1  # false
  fi
}
 
while condition
#     ^^^^^^^^^
#     Function call -- four loop iterations.
do
  echo "Still going: t = $t"
done
 
# Still going: t = 1
# Still going: t = 2
# Still going: t = 3
# Still going: t = 4

Similar to the if-test construct, a while loop can omit the test brackets.
while condition
do
   command(s) ...
done
By coupling the power of the read command with a while loop, we get the handy while read construct, useful for reading and parsing files.
cat $filename |   # Supply input from a file.
while read line   # As long as there is another line to read ...
do
  ...
done
 
# =========== Snippet from "sd.sh" example script ========== #
 
  while read value   # Read one data point at a time.
  do
    rt=$(echo "scale=$SC; $rt + $value" | bc)
    (( ct++ ))
  done
 
  am=$(echo "scale=$SC; $rt / $ct" | bc)
 
  echo $am; return $ct   # This function "returns" TWO values!
  #  Caution: This little trick will not work if $ct > 255!
  #  To handle a larger number of data points,
  #+ simply comment out the "return $ct" above.
} <"$datafile"   # Feed in data file.

A while loop may have its stdin redirected to a file by a < at its end.
A while loop may have its stdin supplied by a pipe.
until
This construct tests for a condition at the top of a loop, and keeps looping as long as that condition is false (opposite of while loop).
until [ condition-is-true ]
do 
 command(s)... 
done
Note that an until loop tests for the terminating condition at the top of the loop, differing from a similar construct in some programming languages.
As is the case with for loops, placing the do on the same line as the condition test requires a semicolon.
until [ condition-is-true ] ; do
Example 11-18. until loop
#!/bin/bash
 
END_CONDITION=end
 
until [ "$var1" = "$END_CONDITION" ]
# Tests condition here, at top of loop.
do
  echo "Input variable #1 "
  echo "($END_CONDITION to exit)"
  read var1
  echo "variable #1 = $var1"
  echo
done  
 
# ------------------------------------------- #
 
#  As with "for" and "while" loops,
#+ an "until" loop permits C-like test constructs.
 
LIMIT=10
var=0
 
until (( var > LIMIT ))
do  # ^^ ^     ^     ^^   No brackets, no $ prefixing variables.
  echo -n "$var "
  (( var++ ))
done    # 0 1 2 3 4 5 6 7 8 9 10 
 
 
exit 0
How to choose between a for loop or a while loop or until loop? In C, you would typically use a for loop when the number of loop iterations is known beforehand. With Bash, however, the situation is fuzzier. The Bashfor loop is more loosely structured and more flexible than its equivalent in other languages. Therefore, feel free to use whatever type of loop gets the job done in the simplest way.

Notes

Iteration: Repeated execution of a command or group of commands, usually -- but not always, while a given condition holds, or until a given condition is met.


SELECT CASE Statement

Fortran has one more selective execution statement, SELECT CASE, and could be very handy if it is used properly. The SELECT CASE statement is also usually referred to as the CASE statement. The following is its syntactic form:
SELECT CASE (selector)
   CASE (label-list-1)
      statements-1
   CASE (label-list-2)
      statements-2
   CASE (label-list-3)
      statements-3
     .............
   CASE (label-list-n)
      statements-n
   CASE DEFAULT
      statements-DEFAULT
END SELECT
where statements-1, statements-2, statements-3, ..., statements-n and statements-DEFAULT are sequences of executable statements, including the SELECT CASE statement itself, and selector is an expression whose result is of type INTEGER, CHARACTER or LOGICAL (i.e., no REAL type can be used for the selector). The label lists label-list-1, label-list-2, label-list-3, ..., and label-list-n are calledcase labels.
A label-list is a list of labels, separated by commas. Each label must be one of the following forms. In fact, three of these four are identical to an extent specifier for substrings:
value
value-1 : value-2
value-1 :
 : value-2
where value, value-1 and value-2 are constants or alias defined by PARAMETER. The type of these constants must be identical to that of the selector.
  • The first form has only one value
  • The second form means all values in the range of value-1 and value-2. In this form, value-1 must be less than value-2.
  • The third form means all values that are greater than or equal to value-1
  • The fourth form means all values that are less than or equal to value-2
The rule of executing the SELECT CASE statement goes as follows:
  • The selector expression is evaluated
  • If the result is in label-list-i, then the sequence of statements in statements-i are executed, followed by the statement following END SELECT
  • If the result is not in any one of the label lists, there are two possibilities:
    • if CASE DEFAULT is there, then the sequence of statements in statements-DEFAULT are executed, followed by the statement following END SELECT
    • if there is no CASE DEFAULT is not there, the statement following END SELECT is executed.
There are some notes for writing good Fortran programs:
  • The constants listed in label lists must be unique
  • CASE DEFAULT is optional. But with a CASE DEFAULT, you are guaranteed that whatever the selector value, one of the labels will be used. I strongly suggest to add a CASE DEFAULT in everySELECT CASE statement.
  • The place for CASE DEFAULT can be anywhere within a SELECT CASE statement; however, put it at the end would be more natural.

Examples

  • The following uses Class to execute a selection. If Class is 1, Freshman is displayed; if Class is 2, Sophomore is displayed; if Class is 3, Junior is displayed; if Class is 4, Senior is displayed; and ifClass is none of the above, Hmmmm, I don't know is displayed. After displaying one of the above, Done is displayed.
·         INTEGER :: Class
·          
·         SELECT CASE (Class)
·            CASE (1)
·               WRITE(*,*)  'Freshman'
·            CASE (2)
·               WRITE(*,*)  'Sophomore'
·            CASE (3)
·               WRITE(*,*)  'Junior'
·            CASE (4)
·               WRITE(*,*)  'Senior'
·            CASE DEFAULT
·               WRITE(*,*)  "Hmmmm, I don't know"
·         END SELECT
·         WRITE(*,*)  'Done'
  • In the following, the value of CHARACTER variable Title is used as a selector. If its value is "DrMD" (resp., "PhD", "MS" and "BS"), then INTEGER variables DrMD (resp., PhD, MS and BS) is increased by 1. Otherwise, Others is increased.
·         CHARACTER(LEN=4) :: Title
·         INTEGER          :: DrMD = 0, PhD = 0, MS = 0, BS = 0, Others = 0
·          
·         SELECT CASE (Title)
·            CASE ("DrMD")
·               DrMD = DrMD + 1
·            CASE ("PhD")
·               PhD = PhD + 1
·            CASE ("MS")
·               MS = MS + 1
·            CASE ("BS")
·               BS = BS + 1
·            CASE DEFAULT
·               Others = Others + 1
·         END SELECT
  • The follow example does not use CASE DEFAULT since the label lists have already covered all possibilities. If the value of Number is less than or equal to -1 (:-1), -1 is stored into Sign. If the value of Number is zero, 0 is stored into Sign. If the value of Number is greater than or equal to 1, 1 is stored into Sign.
·         INTEGER :: Number, Sign
·          
·         SELECT CASE (Number)
·            CASE ( : -1)
·               Sign = -1
·            CASE (0)
·               Sign =  0
·            CASE (1 : )
·               Sign =  1
·         END SELECT
·         WRITE(*,*)  "Sign = ", Sign
  •  If the value of c is one of the first ten letters (in lower case), 'One of the first ten letters' is displayed; if the value of c is one of l, m, n, o, p, u, v, w, x, y, 'One of l, m, n, o, p, u, v, w, x, y' is displayed; if the value of c is one of z, q, r, s, t, 'One of z, q, r, s, t' is displayed; and if the value of c is none of the above, 'Other characters, which may not be letters' is displayed. In the last case, the value of ccould be one of these lower case letters not listed, an upper case letters, a digit, an operator, or any other character. So, if you only want to handle lower case letters, this program is incorrect.
·         CHARACTER(LEN=1) :: c
·          
·         SELECT CASE (c)
·            CASE ('a' : 'j')
·               WRITE(*,*)  'One of the first ten letters'
·            CASE ('l' : 'p', 'u' : 'y')
·               WRITE(*,*)  'One of l, m, n, o, p, u, v, w, x, y'
·            CASE ('z', 'q' : 't')
·               WRITE(*,*)  'One of z, q, r, s, t'
·            CASE DEFAULT
·               WRITE(*,*)  'Other characters, which may not be letters'
·         END SELECT
  • The following program uses the value of Number to determine the value of Range.
·         INTEGER :: Number, Range
·          
·         SELECT CASE (Number)
·            CASE ( : -10, 10 : )
·               Range = 1
·            CASE (-5:-3, 6:9)
·               Range = 2
·            CASE (-2:2)
·               Range = 3
·            CASE (3, 5)
·               Range = 4
·            CASE (4)
·               Range = 5
·            CASE DEFAULT
·               Range = 6
·         END SELECT
Here is the result:
Number
Range
Why?
<= -10
1
CASE ( : -10, 10 : )
-9, -8, -7, -6
6
CASE DEFAULT
-5, -4, -3
2
CASE (-5:-3, 6:9)
-2, -1, 0, 1, 2
3
CASE (-2:2)
3
4
CASE (3, 5)
4
5
CASE (4)
5
4
CASE (3, 5)
6, 7, 8, 9
2
CASE (-5:-3, 6:9)
>= 10
1
CASE ( : -10, 10 : )
Array:
Functions:
http://www.learnqtp.com/new-features-qtp-11-aka-functional-testing-11/

No comments:

Post a Comment