JM Tech Power

jm-tech-power-official/JMLang

A programming language made by JM Tech Power

Public Uncategorized
Clone jm-tech-power-official/jmlang.jmproj
file.jml
# ===== file 库 =====
# 只用了文件原语:read / lines / line / exists / write / append
import "string.jml"

# 带行号打印整个文件(像 cat -n)
func file.print path
    if not exists $path
        out "(文件不存在: " + $path + ")\n"
        ret 0
    end
    set n lines $path
    set i 0
    while $i < $n
        set k $i + 1
        set l $path line $i
        out $k + ": " + $l + "\n"
        set i $i + 1
    end
    ret $n
end

# 复制文件,返回复制了几行
func file.copy src dst
    set n lines $src
    set i 0
    while $i < $n
        set l $src line $i
        if $i == 0
            write $dst , $l
        else
            append $dst , $l
        end
        set i $i + 1
    end
    ret $n
end

# 找第一行包含 text 的行号(从 0 开始),找不到返回 -1
func file.find path text
    set n lines $path
    set i 0
    while $i < $n
        set l $path line $i
        call string.find $l , $text
        if $ret != -1
            ret $i
        end
        set i $i + 1
    end
    ret -1
end

# 数 word 在整个文件里一共出现了几次
func file.count path word
    set n lines $path
    set w len $word
    set total 0
    set i 0
    while $i < $n
        set l $path line $i
        set last len $l
        set last $last - $w
        set j 0
        while $j <= $last
            call string.sub $l , $j , $w
            if $ret == $word
                set total $total + 1
            end
            set j $j + 1
        end
        set i $i + 1
    end
    ret $total
end