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

Dear monks, I am new to perl and I am currently trying to format a file and print this out to a new file. This is the current code I have.
#!/usr/bin/perl -w open (my $SELECT.DAT2, '<', $ARGV[0]) || die "cannot open for reading, + $ ! "; open (my $OUT, '>', $ARGV[0]) || die "cannot open for writing, $ ! "; printf $OUT "NO" "\n", " 'SOURCE' ", "SEC", "Q", "SEC", "\n", "LONG", +"LAT", "DEPTH", "GAP"; close ($SELECT.DAT2); close ($OUT);
Every time I try to run this code I get a syntax error at my. Does the file type matter when using the open command? I understand my code probably has more errors but a little help getting past this first error would be greatly appreciated.

Replies are listed 'Best First'.
Re: Format file
by ikegami (Patriarch) on Jan 21, 2011 at 22:21 UTC
    [ Please include computer text (code, data, output) in <c>..</c> tags. It will preserve the layout. It'll even handle escaping special character for you. ]

    Every time I try to run this code I get a syntax error at my.

    $SELECT.DAT2 is not a valid variable name.

    my $SELECT.DAT2

    means

    (my $SELECT) . "DAT2"

    Contrary to what you said, it's not a syntax error, but it's obviously not what you want. That's why you should always use use strict;. That would have made it a syntax error. It catches so many errors.

    There is a syntax error in your code, though.

    $ perl a.pl String found where operator expected at a.pl line 4, near ""NO" "\n"" (Missing operator before "\n"?) syntax error at a.pl line 4, near ""NO" "\n"" a.pl had compilation errors.

    This is caused by a missing comma.

      Just to clarify, except for the leading sigil ($,@,%, etc.), variable names may only consist of alphanumerics or an underscore. The first character must not be a numeric.

      You will see certain special variables which break this rule (see perlvar) but these are used to control, or get information about, perl behaviour. You cannot create them yourself.
Re: Format file
by toolic (Bishop) on Jan 21, 2011 at 22:30 UTC
    ikegami pointed out your errors. Here are some more tips/links:
    Don't fall into the trap of using a "printf" when a simple "print" would do. The "print" is more efficient and less error prone.
    I also noticed you are opening the same filename $ARGV[0] for both input and output. You probably don't want to do that.