in reply to Read text in file and assign to variable

Just capture the match! You can get rid if the zero-width assertion at the same time:

my $file = '/etc/redhat-release'; # content of /etc/redhat-release # CentOS Linux release 7.6.1810 (Core) open(SOURCE, '<', $file); my ($version) = <SOURCE> =~ m/release (\d)/; close SOURCE; print "The version is: $version\n";

Replies are listed 'Best First'.
Re^2: Read text in file and assign to variable
by maxamillionk (Acolyte) on Jan 24, 2024 at 00:31 UTC
    Thanks for the suggestions. Now I'm trying to understand why the $version variable must have brackets around it.

      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.

      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