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

I have a file parser that reads a configuration file that defines what the record separator is. Something like this:

Config file

RECORDSEPARATOR=\r\n

#!/usr/bin/perl use strict; # read configuration parameters into hash my $recordseparator = $CFG{'RECORDSEPARATOR'}; if (defined $recordseparator && $recordseparator ne '') { $/ = $recordseparator; print STDOUT ":$/:"; # for test } else { $/ = "\n"; }
The above code interprets to $/ = '\r\n' instead of $/ = "\r\n" I know I've done something similar in the past but for the life of me I can't figure this out.

Replies are listed 'Best First'.
Re: Record separator in variable
by haukex (Archbishop) on Jun 06, 2019 at 17:27 UTC

    How you best solve this depends on how many escape sequences you want to support. For example, in this case a simple s/\\n/\n/g; s/\\r/\r/g; might be enough, but there are also modules such as String::Interpolate to give you the full power of Perl's interpolation (which may be too much power for the users of the configuration file). I would stay away from eval unless you are absolutely certain that you can always trust your input.

      I contemplated doing the simple substitution but it's pretty specific to this example. Most customers should use either \n or \r\n for record separators but there is always the chance that one will have an ancient mainframe and send a file with something completely different. I'm looking at String::Interpolate right now, hopefully it will be useful.

        I wrote File::Edit::Portable for purposes such as this. It's quite flexible in reading and writing files with various record separators. It automatically determines the file's record separator, and the record separator of the platform the software is running on.

        Most of the distribution is Object Oriented based, but it has a couple of handy exports for the most basic functionality as well:

        use strict; use warnings; use File::Edit::Portable qw(recsep platform_recsep); $/ = recsep('file.txt'); # set the recsep to that of a file # or $/ = platform_recsep(); # set the recsep to that of the local platfor +m
        Your code must fully support your user documentation for this field and nothing more. Simple substitution may be a good idea. If you allow the full power of perl interpretation, you probably want the module that does that.
        Bill