LoginSignup
3
5

More than 5 years have passed since last update.

PHPでコマンドを実装してみる かんたんseq篇

Posted at

いまのところechoがいちばん行数多い件。
コメントするべきところは… 特にない気がする。

BSDバージョンのseqでもいろいろ機能があるんだけれど、全然実装してないので「かんたん」バージョン。小数点数の処理とか全然してないけどPHPがよしなにやってくれてるので良い感じ。

seq
#!/usr/bin/env php
<?php
namespace zonuexe\UnixCommand;

/**
 * SEQ command
 *
 * @author    USAMI KENTA <tadsan@zonu.me>
 * @license   http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
 * @copyright 2015 USAMI Kenta
 */

if (realpath($_SERVER['SCRIPT_FILENAME']) == realpath(__FILE__)) {
    $argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : [];
    array_shift($argv);

    exit(seq($argv));
}

/**
 * @return int UNIX status code
 */
function seq(array $argv)
{
    $len = count($argv);

    if ($len === 1) {
        $start = 1;
        $step  = 1;
        $last  = array_shift($argv);
    } elseif ($len === 2) {
        $start = array_shift($argv);
        $last  = array_shift($argv);
        $step  = ($start >= $last) ? -1 : 1;
    } elseif ($len === 3) {
        $start = array_shift($argv);
        $step  = array_shift($argv);
        $last  = array_shift($argv);
    } else {
        return 1;
    }

    if ($step == 0) {
        $message = 'seq: zero decrement';
    } elseif (($start < $last) && ($step < 0)) {
        $message = 'seq: needs positive increment';
    } elseif (($start > $last) && ($step > 0)) {
        $message = 'seq: needs negative decrement';
    }

    if (isset($message)) {
        fwrite(STDERR, $message . PHP_EOL);
        return 1;
    }

    foreach (range($start, $last, $step) as $n) {
        echo $n, PHP_EOL;
    }

    return 0;
}
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5