루비
유닉스 클론의 PATH에서 awk를 찾으십시오.
p = ENV['PATH'].split ':'
# Find an executable in PATH.
def find_exec(name)
p.find {|d| File.executable? File.join(d, name)}
end
printf "%s is %s\n", 'awk', find_exec('awk')
죄송합니다!
$ ruby21 find-awk.rb
find-awk.rb:5:in `find_exec': undefined method `find' for nil:NilClass (NoMethodError)
from find-awk.rb:8:in `<main>'
오류에서 우리는 p.find이라는 것을 알고 nil.find있으므로 p이어야합니다 nil. 어떻게 이런일이 일어 났습니까?
Ruby에서는 def로컬 변수에 대한 자체 범위가 있으며 외부 범위에서 로컬 변수를 가져 오지 않습니다. 따라서 과제의 p = ENV['PATH'].split ':'범위가 아닙니다.
정의되지 않은 변수는 일반적으로을 유발 NameError하지만 p특별한 경우입니다. 루비에는라는 전역 메소드가 p있습니다. 따라서 p.find { ... }와 같은 메소드 호출이됩니다 p().find { ... }. 때 p인수가 없습니다, 그것은 반환합니다 nil. (코드 골퍼 p는nil .) 그런 다음을 nil.find { ... }올립니다 NoMethodError.
파이썬으로 프로그램을 다시 작성하여 문제를 해결했습니다.
import os
import os.path
p = os.environ['PATH'].split(':')
def find_exec(name):
"""Find an executable in PATH."""
for d in p:
if os.access(os.path.join(d, name), os.X_OK,
effective_ids=True):
return d
return None
print("%s is %s" % ('awk', find_exec('awk')))
효과가있다!
$ python3.3 find-awk.py
awk is /usr/bin
아마 그것을 인쇄 awk is /usr/bin/awk하고 싶지만 다른 버그입니다.