Perl的DATA文件句柄

有太屢次寫完一個perl程序,須要另外新建一個文件來測試,每次以爲很繁瑣,但又不得不這麼作。沒想到原來perl已經提供瞭解決方案,這就是DATA。php

使用很簡單,見下面這個例子:html

 

1 #!/usr/bin/perl
2 
3 while (<DATA>) {
4         print;
5 }
6 
7 __DATA__
8 hello perl

 

輸出結果: hello perlide

這個用法太方便太perl了,之後不再須要使用新建文件的笨方法了。post

下面是解釋:測試

<IN>能夠從打開的句柄IN中得到數據,<STDIN>能夠從標準輸入接收數據,相似地,<DATA> 文件句柄能夠直接從執行它的腳本中獲取數據,而不是從命令行或者從另外一個文件裏獲取。<DATA> 所讀取的數據保存在每一個腳本末尾的特殊常量__DATA__以後,同時這個常量也標誌着腳本的邏輯結束。url

注意:腳本中有兩個while(<DATA>)將只有前一個起做用,由於前一個已經讀到了文件結尾。好比如下示例:spa

 

 1 #!/usr/bin/perl -w
 2 use strict;
 3 
 4 while (<DATA>) {
 5         print "$_";
 6 }
 7 
 8 while (<DATA>) {
 9         print;
10 }
11 
12 __DATA__
13 hello world

輸出結果:.net

     hello world命令行

而不是:code

     hello world

     hello world

 

 

 

 

__DATA__

A Virtual File In Perl

 

It has been occurred a lot of times that one has to test a code using data from a file. It can be anything like checking for a pattern in a file to taking some input. If you want to check the code without opening the file and reading it. One can use the __DATA__ marker provided by perl as a pseudo-datafile.

Steps to follow:1) At the end of the code use __DATA__ marker and copy paste or write the contents of the file you wish to test exactly from the next line of _DATA_.2) Use while (){ -- your code here -- }.#!/usr/bin/perluse strict;use warnings;while () {chomp $_; print "Found" if $_ =~ /(t\w+)/; print $1;}__DATA__hello there how r uOutput of the above program will be 「there」.

相關文章
相關標籤/搜索