Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: Section of $string into new array

by Eily (Prior)
on Mar 17, 2014 at 17:56 UTC ( #1078643=note: print w/replies, xml ) Need Help??

in reply to Section of $string into new array

I won't give you the whole solution, just tell you what went wrong (at least what I saw) :

Reading through you file

while (<INPUt>) { push @array, $_; }
This does the same thing as : @array = <INPUT>, but since you are processing your file line by line, you don't have to use an array. So in your case you can do:
while (<INPUT>) { if (/$pattern/) # matches work by default on $_ { do something with $_; } }

Your $pattern variable

Your $pattern variable is the empty string, because $pattern = /regex/ means "process /regex/ on the default variable $_ then put the result in $pattern". Since $_ is still empty, the result has to be false. This will work if you just make $pattern a string (or a qred expression in more advanced perl).

While programming, if you need to paste 4 times the same thing in a row, you did it wrong. In a regexp, to repeat some part you can use the {n,m} syntax. Something like /([0-9][0-5]\.){3}/ # three times a two-digit number followed by a dot. Or you can interpolate an inner pattern into the bigger one with something like:

$inner = "([0-5][0-9]|[0-9][1-8])"; $outer = "$inner.$inner.$inner/[0-6]"; # Can also be written $outer = +join('.', $inner x 3) . "[0-6]"
This is not the best solution, but it's probably both simple and effective enough for your needs. And that's still writing several times the same thing (unless you use the alternative syntax), but it's far easier to read, and if a change is required you don't have to copy it 3 times.

Getting the parts (here : numbers) of your string

Then to get the content of your match, you can either use captures (read perlquickre) or keep the split. But here you are splitting on spaces (that's what \s means in a regex), when your pattern doesn't allow spaces (which means the lines you want to split can't have any space). You can split on non-digit characters instead with : split /\D/, $_;


using Data::Dumper is a good thing, but here you're not doing anything with it. Do print the content of your variables when in doubt, this is how you'll be able to solve your problem by yourself, faster than you would by waiting for people to read your code.

And last advice: you can use \d instead of [0-9]

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1078643]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (13)
As of 2018-06-22 14:02 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.