简体   繁体   中英

Splitting lines into individual strings in Perl

Here's my code currently:

    open (MYFILE, "text.txt"); 
    while(<MYFILE>){
        split; 
        if (m,test,){
            print $_; 
        }
    }
    close(MYFILE); 

So if my test.txt file had the following:

line 1: this is a test line
line 2: this has nothing
line 3: oh here's a test

My output is:

line 1: this is a testword line
line 3: oh here's a testphrase

My desired output is just outputting the word with "test" in it or

line 1: testword
line 3: testphrase

I thought by using "split", it changes how Perl reads the input instead of line by line now it would be word by word but it doesn't seem to work. Any thoughts or suggestions?

open (MYFILE, "text.txt"); 
while(<MYFILE>) {
    print grep /test/, split; 
}
close(MYFILE); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM