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

How do I go about printing the strings rather than the list values I am getting from the following code?
#!perl -w # use strict; # Typical line '101|14.95|Short Description|Long Description' open (FH, 'c:/items.pl') or die "Couldn't open file, $!"; while (<FH>){ my ($item_number,$price,$short_desc,$long_desc) = split (/|/); print "$item_number, $short_desc, $price, $long_desc\n"; };
this produces something like '2, 6, 5, 6'

No need to warn me about race conditions, this is to be a simple utility used only by myself.

Replies are listed 'Best First'.
Re: scalar values from split
by grinder (Bishop) on Jan 14, 2002 at 02:40 UTC
    Firstly you need to chomp your input. Secondly, | is regexp-magical. You need to escape it with a backslash in your split.

    Also, you want to mention the name of the file that you fail to open in you open's die clause. That will help in the future. And instead of hardcoding it, you should say something like

    my $file = shift || 'c:/items.pl';
    and then pass $file to your open statement. That way you can run it on a different data file without having to edit your script.

    And I see no race conditions!

    --
    g r i n d e r
    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u';
Re: scalar values from split
by gav^ (Curate) on Jan 14, 2002 at 02:40 UTC
    Very simple, you didn't escape the | character in the split (need to remember that it is a regexp you are using):
    my ($item_number, $price, $short_desc, $long_desc) = split /\|/;
    gav^
Re: scalar values from split
by Juerd (Abbot) on Jan 14, 2002 at 02:58 UTC
    You already get the values as a list of scalars, but you don't split on what you think you split on.
    With your regex, /|/, you match either nothing or nothing (/foo|bar/ matches foo or bar), so you're actually getting individual characters instead of the values you expect to get.
    Escape the pipeline so it'll match a literal pipeline, and it'll work as expected: split /\|/, ....

    hth.

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Re: scalar values from split
by Anonymous Monk on Jan 14, 2002 at 03:07 UTC
    Thanks a lot. It's been forever since I have even looked at perl... I don't know what I was thinking.