Core Function Scanf
(→Example) |
(→Return Value) |
||
Line 22: | Line 22: | ||
=== Return Value === | === Return Value === | ||
+ | |||
+ | ==== If sing the extra params ==== | ||
+ | |||
+ | Success: Returns number of matches and fills in the extra variables (Will make some 0 if there was no match found for that variable). | ||
+ | |||
+ | Failure: Returns 0. | ||
+ | |||
+ | |||
+ | ==== If NOT using the extra params ==== | ||
Success: Returns array of all captured objects from the parsed string. | Success: Returns array of all captured objects from the parsed string. |
Revision as of 17:42, 22 January 2013
Scanf( <expression>, <def> )
Contents |
Description
Parses input from a string according to a format.
Parameters
expression
The string to evaluate.
def
The formation string containing the definition of how to parse the string.
extra ...
Optionally pass in variables by reference that will contain the parsed values.
Return Value
If sing the extra params
Success: Returns number of matches and fills in the extra variables (Will make some 0 if there was no match found for that variable).
Failure: Returns 0.
If NOT using the extra params
Success: Returns array of all captured objects from the parsed string.
Failure: Returns empty array.
Remarks
If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values.
If there are more substrings expected in the format than there are available within str, they will be ignored and you will get what did match.
Example
my $RET = Scanf("X123 Y456", "X%d Y%d"); printr($RET); my $RET = Scanf("Copyright 2009-2011 CompanyName (Multi-Word Message)", "Copyright %d-%d %s (%[^)]"); printr($RET);
Example #1 sscanf() Example
// getting the serial number list($serial) = Scanf("SN/2350001", "SN/%d"); // and the date of manufacturing $mandate = "January 01 2000"; list($month, $day, $year) = Scanf($mandate, "%s %d %d"); println("Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day");
Example #2 sscanf() - using optional parameters If optional parameters are passed, the function will return the number of assigned values.
// get author info and generate DocBook entry $auth = "24\tLewis Carroll"; $n = Scanf($auth, "%d\t%s %s", $id, $first, $last); print("<author id='$id'> <firstname>$first</firstname> <surname>$last</surname> </author>\n");
Example of how to parse a file name without getting the . trapped inside the first %s
$out = scanf('file_name.gif', 'file_%[^.].%s', $fpart1, $fpart2); println("Name '$fpart1' Ext '$fpart2'");
Example of using [] to spawn a character set
$date = 'january-2008'; // notice it is scanning for all characters a-z and uppercase A-Z // so it will match any case of the month name Scanf($date, '%[a-zA-Z]-%d', $month, $year); println("Parsed values: '$month', '$year'");