O’Reilly Mastering Perl 2007 phần 6

Một trong những sử dụng yêu thích của tôi về tự động load đến từ Hash:: AsObject mô-đun bằng Paul Hoffman. Ông thực hiện một số phép thuật ưa thích trong thói quen tự động load của mình vì vậy tôi truy cập các giá trị của một hash với các phím của nó, như tôi bình thường, hoặc như một đối tượng với các phương pháp được đặt tên cho các phím: | no strict refs AUTOLOAD sub _ o - field t0 aTOLOAD a. .oAd _. . if AUTOLOAD set_ w and grep 1 eq elements my field ucfirst l a Auj tU AD sub a _ 0 - field _ l a got0 AUTOLOAD a . die _ o doesnot understand rnethod n Hashes As Objects One of my favorite uses of AUTOLOAD comes from the Hash AsObject module by Paul Hoffman Hea sorne Ọneymạgic ta his AUTOLOAD luulme so l aoooss a hash s values with its keH as Inormally would or as an object with methods named for the keys use HashnAsObject . my hash Hash AsObject- new hash- foo 42 normal access to a hash reference print hash- foo n asanrbject hash- bar 137 h set a value It can even handle multilevel hashes p hash- baz quux 149 hash- baz- quux The trick is thatlhashis really juata normal hash reference that s blessed into a package. When I call a method on that blessed reference it doesn t exist so Perl ends up in Hash AsObject AUTOLOAD. Since it s a pretty involved bit of code to handle lots of special cases I won tshow 7 here butyl does basescUy ahcngl didinthe previous sccrien by deirnme subroutines on the fly. AutoSplit Autosplitting is another variation on the AUTOLOAD technique but I haven t seen it used as much as it used to be. Instead of defining subroutines dynamically AutoSplit takes 154 I Chapter9 Dynamics ubroetimes a module and parses its subroutine definitions and stores each subroutine in its own file. It loads a subroutine s file only when I call that subroutine. In a complicated API with hundreds of subroutines I don t have to make Perl compile every subroutine when I might just want to use a couple of them. Once I load the subroutine Ped does not have to comet ieit agatn d oPercotnpitation unseilnead It. To use AutoSeliP I O i a my sueooutine deOimtions efter the_esc_to ten so Perl doec not parse prcemptO whem. i teSltutoSplOSeo takecSoef definitions and hepeaadsthrm into files perl -r tleAutoSplit aatoipliự aUeanOts 0 e 1 I usually don t ncoelech0 0 a h k .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
30    88    2    03-06-2024
16    77    2    03-06-2024
489    1    1    03-06-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.