Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I am new to perl.....I am having a file like file.txt
abcd pass :10 adlksfkldf kkjfkdf :112 . . .
I want to take the value corresponding to the pass(In this case it is 10)...How can i find it?

Replies are listed 'Best First'.
Re: Regex doubts
by kennethk (Abbot) on Jul 22, 2009 at 16:26 UTC

    Welcome to the Perl community (the language is Perl, the program is perl). What have you tried so far? Can you successfully input and output the data? The monastery is happy to help, though if you post what you've tried so far, it helps us help you by telling us more about your experience level. Read How do I post a question effectively? for more information on what we'd find useful.

    Since your title focuses on regular expressions, I'll assume that's where your issue lies. If we assume all lines of interest consist of 'pass' followed by whitespace, a colon and your desired value which will be an integer, then the following code should be a useful template:

    use strict; use warnings; while (my $line = <DATA>) { if ($line =~ /^pass\s*\:(\d+)/) { print "$1\n"; } } __DATA__ abcd pass :10 adlksfkldf kkjfkdf :112

    See Extracting matches for more information on extracting information. If this code is unclear, I'd be happy to provide additional clarification.

Re: Regex doubts
by xyzzy (Pilgrim) on Jul 22, 2009 at 16:24 UTC
    /^pass\s*:(.*)$/ is one possible solution, but the best regex would be one that specifically matches whatever value you are looking to extract. this regex assumes that the line you want always starts with "pass", then some amount of whitespace, then a colon, then any amount of characters until the end of the line. the value is stored in $1 (it will be overwritten each time)


    Everything is true." "Even false things?" "Even false things are true" "How can that be?" "I dunno man, I didn't do it."
Re: Regex doubts
by mzedeler (Pilgrim) on Jul 22, 2009 at 16:27 UTC