in reply to Re: Read text in file and assign to variable
in thread Read text in file and assign to variable

Thanks for the suggestions. Now I'm trying to understand why the $version variable must have brackets around it.

Replies are listed 'Best First'.
Re^3: Read text in file and assign to variable
by Athanasius (Archbishop) on Jan 24, 2024 at 07:58 UTC

    Hello maxamillionk,

    Perl is context-sensitive, meaning the return value of a function (or, in this case, of a regular expression match) can change depending on what it's assigned to.

    If a match occurs in scalar context, the value returned is the number of matches. In the absence of the /g global modifier, this can only be 1 or 0, success or failure (where failure is indicated by the empty string: ''). my $version = ... puts what follows into scalar context, so the result will be either '1' or '', which is not what you want.

    In list context, the contents (i.e. the value) of the match is returned. Putting parentheses around the variable -- my ($version) = ... -- puts what follows into list context, so the result will be the version number matched (if any), which is what you are looking for here.

    Hope that helps,

    Athanasius <°(((><contra mundum סתם עוד האקר של פרל,

      Thanks Athanasius and kcott. I ended up using ($version) because I consider it more readable.
Re^3: Read text in file and assign to variable
by kcott (Archbishop) on Jan 24, 2024 at 15:36 UTC

    In addition to ++Athanasius' excellent reply, note the examples in my earlier response.

    In the first, I put the match output into a list and assigned the 0th element:

    $version = (<$fh> =~ /(\d)/)[0];

    In the second, I used my ($version) = ..., as already explained.

    — Ken