Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

format

String Expressions and Formatting data in Perl

You can use simple PERL string expressions to set parameters/variables to string values. The most basic string expression sets a variable to a literal string (character) value:

$email="myaddress@mydom.com";

Another basic string expression is to concatenate strings together. In PERL expressions, this is done with the . (period) operator:

$screen="www/".$selected_directory."/".$selected_file;

Or, more simply:

$screen="www/$selected_directory/$selected_file";

You can also use the PERL string functions substr and sprintf:

  • sprintf(FORMAT,LIST) - returns a string formatted by the usual printf conventions. The FORMAT string contains text with embedded field specifiers into which the elements of list are substituted, one per field. Field specifiers are roughly of the form:
    %m.nx
    where the m and n are optional sizes whose interpretation depends on the type of field, and x is one of:
    • s String
    • c Character
    • d Decimal number
    • ld Long decimal number
    • u Unsigned decimal number
    • lu Long unsigned decimal number
    • x Hexadecimal number
    • lx Long hexadecimal number
    • o Octal number
    • lo Long octal number
    • e Exponential format floating-point number
    • f Fixed point format floating-point number
    • g Compact format floating-point number


    Example:
    $order_total=sprintf("%-20s %5.2f","Your total is:",$order_total_amt);
    (Use a negative length in the format specifier to use left justification instead of right justification)

  • substr(EXPR,OFFSET,LENGTH) - the substring of EXPR starting at OFFSET with a length of LENGTH characters (first character is at OFFSET 0).

Examples:

$first_initial_and_comma=substr($first_name,0,1).",";

$order_total=sprintf("%8.2f",$order_subtotal+order_tax);


Regular Expressions

You can use regular expression substitutions to change the value of a variable. For example, to change all strings of whitespace to a single space:

$variable =~ s/\s*/ /;


Miscellaneous Functions

You can use the following miscellaneous functions to set values in your form processor application:

  • sleep(EXPR) - sleeps for EXPR seconds. Useful for "Server push" applications such as animations to pause between multi-part mimes. It doesn't return a value, but in order to invoke it you do need to include it in an expression. Just use a "dummy" variable:
    $dummy_return = sleep(5); # pause for 5 seconds
  • rand(EXPR) - a random fractional number between 0 and the value of EXPR. You should first use srand() to scramble the seed, e.g.:
    $dummy_return=srand(); # return value not used, but form processor only supports perl expressions for setting variable values
    $dice_roll=int(rand(6))+1;
  • srand(EXPR) - sets the seed for the rand function
  • time() - number of non-leap seconds since January 1, 1970