[练习]erlang编程练习1

这边就写点小代码,不求写得很精准能用就好了(跪....

 

统计文件数量:

%%%===============================
%%% @author cc
%%% @description
%%% 查找并统计对应后缀的文件
%%% @end
%%%===============================

-module(seek_file).
-export([seek/1,count/2]).
-define(FLAG,seekfile).

%%程序启动入口,初始化一个监听进程用于统计
seek(Dir) ->  
  Pid=spawn(seek_file,count,[0,[]]),
  case whereis(?FLAG) of
     undefined -> register(?FLAG,Pid);
	 _         -> unregister(?FLAG),register(?FLAG,Pid)
  end,
  seek_inner(Dir,0).

%%搜寻文件的函数  
seek_inner(Dir,No) -> 
   Files=filelib:wildcard(Dir ++ "/*"),
   deal_with(Files,No).
   
%%用于监听的函数   
count(Sum,List) ->
  receive 
    {add,X,File} -> count(Sum+X,[File] ++ List);
	 stop -> io:format("~p~n ~p~n",[Sum,List])
  end.

%%deal_with/2用于对文件进行判断
%%这边用了很多的递归 如果No为0并
%%且列表为空了那么程序就结束了
deal_with([],No) when No/=0 -> ok;

deal_with([],No) -> ?FLAG ! stop;

deal_with([File|Others],No) -> 
  case filelib:is_dir(File) of
     %%间接递归的函数标记为1
     true -> seek_inner(File,1);
	 false -> 
	     case re:run(File,".*\\.java$",[]) of
		    nomatch -> ok;
			{match,_}-> ?FLAG ! {add,1,File}
		  end
   end,
   deal_with(Others,No).
   

    

   输出:

22> c(seek_file).
seek_file.erl:33: Warning: variable 'No' is unused
{ok,seek_file}
23> seek_file:seek("g:/workbench/web").
5
 ["g:/workbench/web/huffman/src/org/cc/mediawork/Huffman.java",
  "g:/workbench/web/huffman/src/org/cc/mediawork/Huffman 2.java",
  "g:/workbench/web/huffman/src/org/cc/mediawork/Huffman - 3.java",
  "g:/workbench/web/huffman/src/org/cc/mediawork/Huffman - .java",
  "g:/workbench/web/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/first/org/apache/jsp/index_jsp.java"]
stop

 

你可能感兴趣的:(erlang)