2010年8月10日星期二

Linux systems with PHP scripts to read the text input and

As a Linux system command line Perl script to explain the language of choice for the day is over. Today, we have more options, including Python, Ruby and PHP. If you write PHP code for the Web site, and familiar with the language, you will find the command line to use PHP's speed, the effect of a good surprise.

In the script, any script language, one of the biggest function is to manipulate files and obtain user input. PHP deal with as much grace as any other scripting language.

For example, the use of PHP in the script to read user input during the processing, use:

#! / Usr / bin / php

function read_input ()

(

$ Fp = fopen ("/ dev / stdin", "r");

$ Input = trim (fgets ($ fp, 255));

fclose ($ fp);

return $ input;

)

printf ("Please supply your name:");

$ Name = read_input ();

printf ("Hello, $ name.");

?>

Defined above read_input () function is extracted from the STDIN input, stored in the $ input variable in order to guide and followed all the blank space, and then return.

The same principle can also be used in standard documents read and operate; remember, for Linux, STDIN is just another file it (accordingly, the above example the opening / dev / stdin is true).

#! / Usr / bin / php

if (file_exists ($ argv [1]))

(

$ File = $ argv [1];

) Else (

printf ("ERROR: File '$ file' does not exist!");

exit 1;

)

$ Data = file ($ file);

$ C = 1;

foreach ($ data as $ line)

(

printf (sprintf ("[% s]:% s", $ c, $ line));

$ C + +;

)

In the example above, PHP script will read the file passed to the command line, each line, and follow the current lines of its output. If the file does not exist, the script will print an error and return code 1 and exit (1 for error; in normal operation, the script will return exit code 0). file () function is used here, it reads the file per line, an array (in this case, the array as $ data), then for foreach () statement, in the array cycle time is in the file line.

PHP is no longer strictly Web-based programming. We can easily apply it to write command-line script, is both flexible and fast. Similarly, almost all Web script you can use to operate, for example, database operations, can easily apply PHP's command-line script to complete.

没有评论:

发表评论