Often combining split() and regex is very powerful. And can result in a regex that is easier to write and understand. The code below essentially says: delete the parens (if any) around the 2nd thing in the line where "things" are sequences of characters separated by spaces. This may or may not be all that you need, but without more than one test case, I have no way to determine that.
Also there can be reasons why it is desirable to "slurp" all of the data in a file into a memory resident array as in @fileinput=<$file>;, but in general when processing files line by line, this is not a good idea as it wastes memory and is slower than: read line, process line, read next line, etc. Also when doing a file operation, like "open" check the status of the open - it is very possible that an "open()" can fail: file does not exits, wrong permissions, etc.
As Grandfather points out, DATA is an already open file handle that can read data from within your Perl code as shown below. This is extremely useful for testing.
#!/usr/bin/perl -w use strict; while (<DATA>) { my ($id, $num, $rest) = split(/\s+/, $_, 3); $num =~ tr/()//d; #deletes parens in num field print "$id $num $rest"; } #prints: #PP: 899040 Jane Smith #PP: 899040 Jane (Smith) #PP: 899040 Jane (Smith) __DATA__ PP: (899040) Jane Smith PP: 899040 Jane (Smith) PP: (899040) Jane (Smith)
In reply to Re: Extracting the number in a file and get the value and output to the other file
by Marshall
in thread Extracting the number in a file and get the value and output to the other file
by allison
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |