in reply to Input Formats

Says jakeeboy:
I was wondering if perl formats could be used in reverse
Yes; it's called a regex.

Instead of this:

FORMAT INPUT = @<<<<<<< Year Sales: @#######.## @||||| @>>>>>>>> .
You write this:
($text1, $sales, $inv_number, $text2) = $input =~ /^(........) Year Sales: (\d\d\d\d\d\d\d\d\.\d\d) (. +.....) (.........)$/;

Replies are listed 'Best First'.
Re: Re: Input Formats
by mischief (Hermit) on Dec 28, 2000 at 16:01 UTC
    After reading japhy's Code Smarter, I thought maybe unpack might do this job more efficiently than a regex? Something like this maybe:
    $record = "abcdefghk Year Sales: 0123456.01 peter x193v 20i39 + "; for (unpack "A9 A17 A10 A5 A6 A1 A*", $record) { $i++; print $_,"\n" if $i%2; }

    I don't really know if unpack would be more efficient or not, but it might show an increase in speed if there was a large record set.

    And just to give an example of how you might start doing this with substr:

    @format=(9, 17, 10, 5, 6, 1, 11); print_record($record, @format); sub print_record { $record = shift; @format = @_; for (@format) { $i++; $value = substr($record, $pointer, $_); $pointer += $_; print "value: '$value'\n" if $i % 2; } }

    This method means that you're liable to have spaces padding variable length data though. Not exactly difficult to get rid of, but not quite as neat.

    I guess it would also be fairly easy to use whatever method you choose to deconstruct a format definition itself.